Ethan Elzenaar-Adams Ethan Elzenaar-Adams - 1 month ago 13
Python Question

Replace vowels in string with word "oodle" without replacing the vowels in "oodle"

This is my code so far.

line = input("Enter a sentence:\n")
for i in range(0,len(line)):
line = line.replace('a', 'oodle')
line = line.replace('e', 'oodle')
line = line.replace('i', 'oodle')
line = line.replace('o', 'oodle')
line = line.replace('u', 'oodle')
print(line)


However, it replaces the o's and e's in the word "oodle" after replacing them. How can I make it not?

Answer

Use re.sub:

>>> re.sub(r'[aeiou]', 'ooddle', "test")
'tooddlest'

re.sub replaces the strings at once, so you won't replace the same string twice.

Comments