Change language

Python | Split strings in a list with the same prefix in all elements

| |

Method # 1: Using List Comprehension + List Slicing

This task can be accomplished using List Comprehension and List Slicing. A list of lists can be used to remove unwanted letters, and a list comprehension can be used to extend logic to the entire line.

# Python3 demo code
# Split lines in the list
# Using a list comprehension + slicing a list

 
# initializing list

test_list = [ ’Rs.25’ , ’Rs.100’ , ’ Rs. 143’ , ’Rs.12’ , ’Rs.4010’ ] < / code>

 
# print original list

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

  
# use list comprehension + list slicing
# Split lines in list

res = [sub [ 3 :] for sub in test_list]

 
# print result

print "The list after string slicing:" + str (res))

Output:

 The original list: [’Rs.25’,’ Rs.100’, ’Rs.143’,’ Rs.12’, ’Rs.4010’] The list after string slicing: [’25’,’ 100’, ’143’,’ 12’, ’4010’] 

Method # 2: Using map () + slicing + lambda

This particular task can be accomplished using the map function. The task of doing the same thing for each row is handled by the lambda and display functions.

# Python3 demo code
# Split lines in the list
# Using map () + slicing + lambda

 
# initializing list

test_list = [ ’Rs.25’ , ’Rs.100’ , ’ Rs.143’ , ’Rs.12’ , ’ Rs.4010’ ]

 
# printing the original list

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

 
# using map () + slicing + lambda
# Split lines in the list

res = list ( map ( lambda sub: sub [ 3 :], test_list))

 
# print result

print ( "The list after string slicing:" + str (res))

Output:

 The original list: [’Rs.25’,’ Rs.100’, ’Rs.143’,’ Rs.12’, ’Rs.4010’] The list after string slicing: [’ 25’, ’100 ’,’ 143’, ’12’,’ 4010’] 

Python | Split strings in a list with the same prefix in all elements Python functions: Questions

Python | Split strings in a list with the same prefix in all elements split: 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