Sometimes, we want to change one character in a string with Python.
In this article, we’ll look at how to change one character in a string with Python.
How to change one character in a string with Python?
To change one character in a string with Python, we can convert the string to a list with list.
Then we change the character at the given list index.
And then we convert the list back to a string with join.
For instance, we write:
text = 'abcdefg'
new = list(text)
new[6] = 'W'
s = ''.join(new)
print(s)
We call list with text to convert text to the new list.
Then we set the character at index 6 of the list to 'W'.
Next, we call ''.join with new to convert new back to a string and assign the returned string to s.
Therefore, s is 'abcdefW'.
Conclusion
To change one character in a string with Python, we can convert the string to a list with list.
Then we change the character at the given list index.
And then we convert the list back to a string with join.