In Python, strings are immutable.
What is the standard idiom to walk through a string character-by-character and modify it?
The only methods I can think of a
If I ever need to do something like that I just convert it to a mutable list
For example... (though it would be easier to use sort (see second example) )
>>> s = "abcdfe"
>>> s = list(s)
>>> s[4] = "e"
>>> s[5] = "f"
>>> s = ''.join(s)
>>> print s
abcdef
>>>
# second example
>>> s.sort()
>>> s = ''.join(s)
I'd say the most Pythonic way is to use map():
s = map(func, s) # func has been applied to every character in s
This is the equivalent of writing:
s = "".join(func(c) for c in s)
string.translate
is probably the closest function to what you're after.
>>> mystring = "Th1s 1s my str1ng"
>>> mystring.replace("1", "i")
'This is my string'
If you want to store this new string you'll have to mystring = mystring.replace("1", "i")
. This is because in Python strings are immutable.
I did that like this:
import tempfile
import shutil
...
f_old = open(input_file, 'r')
with tempfile.NamedTemporaryFile() as tmp:
for line in f_old:
tmp.write(line.replace(old_string, new_string))
f_old.close()
tmp.flush()
os.fsync(tmp)
shutil.copy2(tmp.name, input_file)
tmp.close()
Assigning a particular character to a particular index in a string is not a particularly common operation, so if you find yourself needing to do it, think about whether there may be a better way to accomplish the task. But if you do need to, probably the most standard way would be to convert the string to a list, make your modifications, and then convert it back to a string.
s = 'abcdefgh'
l = list(s)
l[3] = 'r'
s2 = ''.join(l)
EDIT: As posted in bstpierre's answer, bytearray
is probably even better for this task than list
, as long as you're not working with Unicode strings.
s = 'abcdefgh'
b = bytearray(s)
b[3] = 'r'
s2 = str(b)