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