在Python中交换字符串列表中的“单词”

时间:2013-11-02 17:33:17

标签: python string list

所以,假设我有一个清单:

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

我想用“请勿打扰”切换“DND”,有没有快速简便的方法呢? 我已经阅读了Python的方法列表,但我一定忽略了一些东西,我找不到任何可以帮助我的东西。

1 个答案:

答案 0 :(得分:7)

使用str.replace替换字符串:

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

使用List comprehension,您会得到一个新的列表,其中每个项目字符串都被替换为:

>>> 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!']