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?
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.
We can replace multiple characters in a string using replace() , regex. sub(), translate() or for loop in python.
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.
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'
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