Change language

Python | Sequential string comparison

|

Method # 1: Using zip () + loop
This is one way to accomplish this task. In this we use zip () to concatenate an item and its next item, and then compare for the truth and store it in the list.

# Python3 demo code work
# Consecutive string comparison
# using zip () + loop

 
# initialize the list

test_list = [ ’ gfg’ , ’gfg’ , ’ is’ , ’best’ , ’ best’ , ’for’ , ’geeks’ , ’ geeks ’ ]

  
# print original list

print ( " The original list: " + str (test_list))

 
# Consecutive string comparison
# using zip () + loop

res = []

for i, j in zip (test_list, test_list [ 1 :]):

  if i = = j:

res.append (i)

  
# print result

print ( " List of Consecutive similar elements: " + str (res))

Exit :

 The original list: [’gfg’,’ gfg’, ’is’,’ best’, ’best’,’ for’, ’geeks’,’ geeks’] List of Consecutive similar elements: [’gfg’,’ best’, ’geeks’] 

Method # 2: Using comprehension list + zip ()
This task can also be done with using the above functions. In this, we take a one-liner approach to solve this problem using a list comprehension. The method is the same as above.

# Python3 code to demonstrate how it works
# Consecutive string comparison
# using zip () + list comprehension

 
# initialize the list

test_list = [ ’gfg’ , ’ gfg ’ , ’ is’ , ’best’ , ’ best’ , ’for’ , ’ geeks’ , ’geeks’ ]

  
# printing the original list

print ( "The original list:" + str (test_list))

 
# Consecutive string comparison
# using zip () + list comprehension

res = [i for (i, j) in zip (test_list, test_list [ 1 :]) if i = = j]

 
# print result

print ( "List of Consecutive similar elements:" + str (res))

Output:

 The original list: [’gfg’,’ gfg’, ’is’,’ best’, ’best’,’ for’, ’geeks ’,’ geeks’] List of Consecutive similar elements: [’gfg’,’ best’, ’geeks’] 

Python | Sequential string comparison Python functions: Questions

Python | Sequential string comparison String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method