查找和替换lis中的字符串值

2024-04-26 05:39:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个单子:

words = ['how', 'much', 'is[br]', 'the', 'fish[br]', 'no', 'really']

我想用一些类似于<br />的奇异值替换[br],从而得到一个新列表:

words = ['how', 'much', 'is<br />', 'the', 'fish<br />', 'no', 'really']

Tags: thenobrltgt列表ishow
3条回答
words = [w.replace('[br]', '<br />') for w in words]

这些被称为List Comprehensions

除了列表理解,您还可以尝试映射

>>> map(lambda x: str.replace(x, "[br]", "<br/>"), words)
['how', 'much', 'is<br/>', 'the', 'fish<br/>', 'no', 'really']

例如,您可以使用:

words = [word.replace('[br]','<br />') for word in words]

相关问题 更多 >