Asked By – kostia
What is the easiest way in Python to replace a character in a string?
text = "abcdefg"; text = "Z"; ^
Now we will see solution for issue: Changing one character in a string
Don’t modify strings.
Work with them as lists; turn them into strings only when needed.
>>> s = list("Hello zorld") >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd'] >>> s = 'W' >>> s ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'] >>> "".join(s) 'Hello World'
Python strings are immutable (i.e. they can’t be modified). There are a lot of reasons for this. Use lists until you have no choice, only then turn them into strings.