Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple characters in a string at once

Tags:

python

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

like image 641
jeff Avatar asked Oct 08 '17 09:10

jeff


People also ask

How do I replace multiple characters in a string?

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.

How do I replace multiple characters in a string in SQL?

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() .

How do you replace multiple values in a string in Python?

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.


1 Answers

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.
like image 50
Eric Duminil Avatar answered Sep 18 '22 15:09

Eric Duminil