python string in-place modification

Question:

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)
Asked By: nos

||

Answers:

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'21','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?

Answered By: Nix

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)
Answered By: Andrew Clark
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.