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

I want to search for the element containing the word Wednesday and replace that element with a line break at the beginning. So:

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

Any help would be great. Everything I've tried has not worked. Thanks.

3 Answers 3

5

Processing the items in a list to make a new list calls for a list comprehension. Combine it with the x if y else z conditional expression to modify the items as you want.

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]
Sign up to request clarification or add additional context in comments.

Comments

2

You can use endswith in a list comprehension:

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

Output:

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

1 Comment

in is better than endswith
2

List comprehension, and conditional expressions:

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

Example:

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']

As a side note, setting your variable as list is a bad idea, as it shadows the builtin list type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.