Python | Add suffix / prefix to strings in a list

Python Methods and Functions | String Variables

Method: Using the + operator + list comprehension

In this task, we simply add a string to the back or front position using the + operator, and list comprehension is used to iterate over all elements.

# Python3 code to demonstrate how it works
# Add suffix / prefix to lines in the list
# Using the comprehension list + operator & quot; + & quot;

  
# initializing list

test_list = [ 'a' , 'b' , ' c' , 'd' ]

  
# print list

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

 
# initializing append_str

append_str = 'gfg'

 
# Add suffix / prefix to lines in the list

pre_res = [append_str + sub for sub in test_list]

suf_res = [sub + append_str for sub in test_list]

 
# Print result

print ( "list after prefix addition:" + str (pre_res))

print ( "list after suffix addition:" + str (suf_res))

Output:

 The original list: ['a', 'b',' c', 'd'] list after prefix addition: [' gfga', 'gfgb',' gfgc', 'gfgd'] list afterix addition: [' agfg', 'bgfg',' cgfg ',' dgfg']