如果列表中的元素包含字符串

时间:2018-01-23 23:47:54

标签: python python-2.7

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

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

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

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

3 个答案:

答案 0 :(得分:4)

处理列表中的项目以创建新列表需要列表推导。将其与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]

答案 1 :(得分:2)

您可以在列表理解中使用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']

答案 2 :(得分:2)

列表理解和条件表达式:

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类型。