Home > OS >  appending a string to a list of strings if the string in the list is equal to some variable in pytho
appending a string to a list of strings if the string in the list is equal to some variable in pytho

Time:11-20

a=['item1', 'item2', 'item3', ...]
b='item2'

now if I want to say add * to the beginning and end of 'item2' in the list 'a' how can i do that?

CodePudding user response:

You could use a list comprehension:

>>> a = ['item1', 'item2', 'item3']
>>> b = 'item2'
>>> c = [f'*{s}*' if s == b else s for s in a]
>>> c
['item1', '*item2*', 'item3']
  • Related