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/