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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.89to1.234.567,89. Guido has endorsed this as a reasonable technique.