List comprehension allows you to create a new modified list from an old list. My example is a tad tricky to someone new, the .split() makes it all happen and I added some other things inside the list comprehension too.
So blah is set to a string, then a temp list is made so we can check each index using .split() which defaults to a space separator so we can filter by words. Without the .split() the for loop would check each character and not words. Output is a modified bleh list with all remaining words in capitols and we replace the ? with a !.
blah = 'I want to go to hell or Alaska?' # print(blah) to see why .split() is used bleh = [c.upper().replace('?', '!') for c in blah.split() if c != 'hell' and c != 'or'] print(bleh) # ['I', 'WANT', 'TO', 'GO', 'TO', 'ALASKA!'] # To print like a new string print(' '.join(bleh)) # I WANT TO GO TO ALASKA!
I love list comprehension.