0

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)
1
  • I hope you aren't just wanting str.replace? Commented Feb 25, 2012 at 3:36

2 Answers 2

2

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:

x = 'abc'
result = x[1] + x[0] + x[2:]

or (personal fav)

import re
re.sub('(.)(.)', r'\2\1','abc')

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).

from UserString import MutableString
x = MutableString('abc')
x[1], x[0] = x[0], x[1]
>>>>'bac'

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?

Sign up to request clarification or add additional context in comments.

6 Comments

no. I just want to change the string in-place. In that case, would breaking it into list of char the best option?
It inherently is a list of strings. You dont need to convert it to a list.
@nos - Python is not C, you don't have direct access to a string to modify it in-place. Whatever else you think you are doing with lists and slices etc., you are not editing a string in-place. What does that mean? Stop worrying about "in-place"-ness of your update, just make a new string like in Nix's first example and move on to the other more important parts of your program.
@nos: But why do you want to change the string in place? Python is not really built for it. You are fighting against the language instead of using it to your advantage. Just replace the string with a new one and be done with it.
@nos: but munching the string to a list and swapping the 1st two elts isn't an "inplace" update either as you still have to join the list back into a string & reassign. So why not follow nix's solution?
|
1

You cannot modify strings in place, they are immutable. If you want to modify a list in place, you can do it like in your example, or you could use slice assignment if the elements you want to replace can be accessed with a slice:

tmp = list('abc')
tmp[0:2] = tmp[1::-1]   # replace tmp[0:2] with tmp[1::-1], which is ['b', 'a']
result = ''.join(tmp)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.