所以,假设我有一个清单:
excuses=['Please go away, DND',
'Didn't you hear me? DND',
'I said DND!']
我想用“请勿打扰”切换“DND”,有没有一种快速简便的方法可以做到这一点?我已经阅读了一些 Python 的方法列表,但我一定忽略了一些东西,我没有找到任何可以帮助我的东西。
用于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!']