Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple strings at the same time

Tags:

python

Lets say I have this string "abcd"

Now I want to replace all 'a's with a 'd' and I want to replace all 'd's with an 'a'. The problem is that string.replace does not work in this situation.

"abcd".replace('a','d').replace('d','a')

abca

Expected output is "dbca"

How would I acheive this?

like image 226
John Smith Avatar asked Apr 06 '18 04:04

John Smith


People also ask

How do I replace multiples 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.

Can you replace multiple strings in Python?

We can replace multiple characters in a string using replace() , regex. sub(), translate() or for loop in python.

How do you replace all occurrences?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag. replaceAll() method is more straight forward.


1 Answers

You could use .translate().

Return a copy of the string in which each character has been mapped through the given translation table.

https://docs.python.org/3/library/stdtypes.html#str.translate

Example:

>>> "abcd".translate(str.maketrans("ad","da"))
'dbca'
like image 103
Loocid Avatar answered Sep 23 '22 08:09

Loocid