Suppose I want to change ‘abc’ to ‘bac’ in Python. What would be the best way to do it?
I am thinking of the following
tmp = list('abc')
tmp[0],tmp[1] = tmp[1],tmp[0]
result = ''.join(tmp)
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.
You are never editing a string “in place”, strings are immutable.
You could do it with a list but that is wasting code and memory.
Why not just do:
or (personal fav)
This might be cheating, but if you really want to edit in place, and are using 2.6 or older, then use MutableString(this was deprecated in 3.0).
With that being said, solutions are generally not as simple as ‘abc’ = ‘bac’ You might want to give us more details on how you need to split up your string. Is it always just swapping first digits?