Mark
Mark

Reputation: 25

Swapping "words" in a list of strings in Python

So, let's say I have a list:

excuses=['Please go away, DND', 
         'Didn't you hear me? DND', 
         'I said DND!']

and I want to switch "DND" with "do not disturb", is there a quick and easy way to do that? I've read a little through the list of methods for Python, but I must've overlooked something, I didn't find anything that could help me.

Upvotes: 0

Views: 5031

Answers (1)

falsetru
falsetru

Reputation: 369034

Use str.replace to substitute string:

>>> "Please go away, DND".replace('DND', 'do not disturb')
'Please go away, do not disturb'

And using List comprehension, you get a new list with each item string substituted:

>>> excuses = ["Please go away, DND", "Didn't you hear me? DND", "I said DND!"]
>>> [excuse.replace('DND', 'do not disturb') for excuse in excuses]
['Please go away, do not disturb', "Didn't you hear me? do not disturb", 'I said do not disturb!']

Upvotes: 7

Related Questions