Say I have a string, "ab"
.
I want to replace "a"
with "b"
and "b"
with "a"
in one swoop.
So in the end, the string should be "ba"
and not "aa"
or "bb"
and not use more than one line. Is this doable?
Show activity on this post. var str = "I have a cat, a dog, and a goat."; str = str. replace(/goat/i, "cat"); // now str = "I have a cat, a dog, and a cat." str = str. replace(/dog/i, "goat"); // now str = "I have a cat, a goat, and a cat." str = str.
Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.
To replace multiple values in a DataFrame we can apply the method DataFrame. replace(). In Pandas DataFrame replace method is used to replace values within a dataframe object.
It replaces all the occurrences of the old sub-string with the new sub-string. In Python, there is no concept of a character data type. A character in Python is also a string. So, we can use the replace() method to replace multiple characters in a string.
When you need to swap variables, say x and y, a common pattern is to introduce a temporary variable t to help with the swap: t = x; x = y; y = t
.
The same pattern can also be used with strings:
>>> # swap a with b >>> 'obama'.replace('a', '%temp%').replace('b', 'a').replace('%temp%', 'b') 'oabmb'
This technique isn't new. It is described in PEP 378 as a way to convert between American and European style decimal separators and thousands separators (for example from 1,234,567.89
to 1.234.567,89
. Guido has endorsed this as a reasonable technique.
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