替换列表中包含字符串的元素

2024-10-01 00:22:44 发布

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

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

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

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

任何帮助都会很好。我尝试过的一切都没有奏效。谢谢。你知道吗


Tags: the元素hellonewis单词listtomorrow
3条回答

处理列表中的项目以生成新列表需要列表理解。将它与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]

列出理解和条件表达式:

new_list = ['\n{}'.format(i) if 'Wednesday' in i else i for i in list_]

示例:

In [92]: l = ['the dog ran', 'tomorrow is Wednesday', 'hello sir']

In [93]: ['\n{}'.format(i) if 'Wednesday' in i else i for i in l]
Out[93]: ['the dog ran', '\ntomorrow is Wednesday', 'hello sir']

顺便说一下,将变量设置为list是个坏主意,因为它会隐藏内置的list类型。你知道吗

您可以在列表理解中使用endswith

l = ['the dog ran', 'tomorrow is Wednesday', 'hello sir']
new_l = ['/n'+i if i.endswith('Wednesday') else i for i in l]

输出:

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

相关问题 更多 >