What is the easiest way in Python to replace a character in a string?
For example:
text = \"abcdefg\";
text[1] = \"Z\";
^
I would like to add another way of changing a character in a string.
>>> text = '~~~~~~~~~~~'
>>> text = text[:1] + (text[1:].replace(text[0], '+', 1))
'~+~~~~~~~~~'
How faster it is when compared to turning the string into list and replacing the ith value then joining again?.
List approach
>>> timeit.timeit("text = '~~~~~~~~~~~'; s = list(text); s[1] = '+'; ''.join(s)", number=1000000)
0.8268570480013295
My solution
>>> timeit.timeit("text = '~~~~~~~~~~~'; text=text[:1] + (text[1:].replace(text[0], '+', 1))", number=1000000)
0.588400217000526