Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace two things at once in a string?

Tags:

python

string

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?

like image 463
WhatsInAName Avatar asked Dec 31 '11 07:12

WhatsInAName


People also ask

How do you replace two values in a string?

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.

How do I replace multiple substrings in a string?

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.

How do you replace multiple values in Python?

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.

Can a string be replaced twice?

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.


1 Answers

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.

like image 70
Raymond Hettinger Avatar answered Sep 24 '22 16:09

Raymond Hettinger