0

I have a list like this:

list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']

I want for example to replace ‘hello’ and ‘halo’ with ‘welcome’, and ‘goodbye’ and ‘bye bye’ with ‘greetings’ so the list will be like this:

list1 or newlist = ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?']

how can I do that the shortest way?

I tried this, but it didn’t work unless I convert my list to string first but I want it to be list, any way I converted to string and changed the words and then I tried to convert it back to list but wasn’t converted back properly.

dNm
  • 23
  • 4

3 Answers3

2

if the substitutions can easily be grouped then this works:

list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']
new_list = []
group1 = ('hello', 'halo')
group2 = ('goodbye', 'bye bye')

for word in list1:
    if word in group1:
        new_list.append('welcome')
    elif word in group2:
        new_list.append('greetings')
    else:
        new_list.append(word)

print(new_list)
# ['welcome', 'welcome', 'greetings', 'greetings', 'how are you?']
willwrighteng
  • 1,411
  • 11
  • 25
1

I see this question is marked with the re tag, so I will answer using regular expressions. You can replace text using re.sub.

>>> import re
>>> list1 = ",".join(['hello', 'halo', 'goodbye', 'bye bye', 'how are you?'])
>>> list1 = re.sub(r"hello|halo", r"welcome", list1)
>>> list1 = re.sub(r"goodbye|bye bye", r"greetings", list1)
>>> print(list1.split(","))
['welcome', 'welcome', 'greetings', 'greetings', 'how are you?']
>>> 

Alternatively you can use a list comprehension

["welcome" if i in ["hello","halo"] else "greetings" if i in ["goodbye","bye bye"] else i for i in list1]
1

List comprehension would be the shortest way...

list1 = ['hello', 'halo', 'goodbye', 'bye bye', 'how are you?']
newlist = ['welcome' if i == 'hello' or i == 'halo' else 'greetings' if i == 'goodbye' or i == 'bye bye' else i for i in list1 ]
print(newlist)
Robin Sage
  • 969
  • 1
  • 8
  • 24