Skip to main content
 首页 » 编程设计

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

2025年05月04日21zfyouxi

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]