python - 如果列表中包含字符串,则替换列表中的元素

标签 python python-2.7

list = ['the dog ran', 'tomorrow is Wednesday', 'hello sir']

我想搜索包含单词 Wednesday 的元素,并在开头用换行符替换该元素。所以:

new_list = ['the dog ran', '/ntomorrow is Wednesday', 'hello sir']

任何帮助都会很棒。我尝试过的一切都没有奏效。谢谢。

最佳答案

处理列表中的项目以创建新列表需要列表理解。将它与 x if y else z 条件表达式组合,以根据需要修改项目。

old_list = ['the dog ran', 'tomorrow is Wednesday', 'hello sir']
new_list = [('\n' + item) if "Wednesday" in item else item for item in old_list]

关于python - 如果列表中包含字符串,则替换列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48412711/

相关文章:

python - 使矩阵对称、就地与异地

Python - 将数字与 boolean 值进行比较(始终返回 false)

Python 和 Opswat

python - 如何聚合具有列值上限的行?

python - 用查询结果填充字典

python - map 与列表;为什么会有不同的行为?

python - 将 unicode 对象与字符串对象进行比较时的奇怪行为

python-2.7 - 如何使用查询游标跳转到特定页面?

python - tkinter 文本小部件中的撤消功能

python - 'yield all the output from a generator' 有简写吗?