Python | Remove string prefix from list

Python Methods and Functions | string prefix | String Variables

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: StackOverflow Questions

add a string prefix to each value in a string column using Pandas

I would like to append a string to the start of each value in a said column of a pandas dataframe (elegantly). I already figured out how to kind-of do this and I am currently using:

df.ix[(df["col"] != False), "col"] = "str"+df[(df["col"] != False), "col"]

This seems one hell of an inelegant thing to do - do you know any other way (which maybe also adds the character to rows where that column is 0 or NaN)?

In case this is yet unclear, I would like to turn:

    col 
1     a
2     0

into:

       col 
1     stra
2     str0

Get Solution for free from DataCamp guru