Change language

Python | Remove string prefix from list

| |

Method # 1: Using loop + remove () + startswith ()
Combining the above functions can solve this problem. In this, we remove elements that start with a specific prefix, available using a loop, and return the modified list.

# Python3 demo code
# Remove prefix lines from the list
# using loop + remove () + starts with ()

 
# initialize the list

test_list = [ ’xall’ , ’xlove’ , ’ gfg’ , ’xit’ , ’is’ , ’best’ ]

  
# print original list

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

  
# initialize prefix

pref = ’x’

 
# Remove prefix strings from the list
# using loop + delete () + starts with ()

for word in test_list [:]:

if word.startswith (pref):

test_list.remove (word)

  
# print result

print ( "List after removal of Kth character of each string:" + str (test_list))

Output:

 The original list: [’xall’,’ xlove’, ’gfg’,’ xit’, ’is’,’ best’] List after removal of Kth character of each string: [’gfg’,’ is’, ’best’] 

Method # 2: Using the comprehension list + startswith()
This is another a way to accomplish this task. However, we are not doing in-place deletion, instead we are re-creating the list with no elements matching the prefix.

# Python3 code to demonstrate how it works
# Remove prefix lines from the list
# use comprehension list + startwith ()

 
# initialize the list

test_list = [ ’xall’ , ’ xlove’ , ’gfg’ , ’xit’ , ’ is’ , ’be st’ ]

 
# print original list

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

 
# initialize prefix

pref = ’x’

 
# Remove prefix strings from the list
# use comprehension list + startwith ( )

res = [ele for ele in test_list if not ele.startswith (pref )]

 
# print result

print ( "List after removal of Kth character of each string:" + str (res))

Output:

 The original list: [’xall’,’ xlove’, ’gfg’,’ xit’, ’is’,’ best’] List after removal of Kth character of each string: [’gfg’,’ is’, ’best’] 

Python | Remove string prefix from list Python functions: Questions

Python | Remove string prefix from list string prefix: 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