Please advise if the following code works. Mine seems not working at all
string = str(input('Enter something to change'))
replacing_words = 'aeiou'
for i in replacing_words:
s = string.replace('replacing_words', ' ')
print(s)
My intension here is to replace all vowels in the string with a space. If this is a wrong code, could someone assist with right codes and explanation, why it didn't work?
Thank you
Use the replace() method to replace multiple characters in a string, e.g. str. replace(/[. _-]/g, ' ') . The first parameter the method takes is a regular expression that can match multiple characters.
If you wanted to replace the words with blank string, go with REGEXP_REPLACE() . If you want to replace the words with other words, for example replacing & with and then use replace() . If there are multiple words to be replaced, use multiple nested replace() .
Method 3: Replace multiple characters using re.subn() is similar to sub() in all ways, except in its way of providing output. It returns a tuple with a count of the total of replacement and the new string rather than just the string.
You could define a translation table. Here's a Python2 code:
>>> import string
>>> vowels = 'aeiou'
>>> remove_vowels = string.maketrans(vowels, ' ' * len(vowels))
>>> 'test translation'.translate(remove_vowels)
't st tr nsl t n'
It's fast, concise and doesn't need any loop.
For Python3, you'd write:
'test translation'.translate({ord(ch):' ' for ch in 'aeiou'}) # Thanks @JonClements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With