What is the easiest way in Python to replace a character in a string?
For example:
text = \"abcdefg\";
text[1] = \"Z\";
^
Strings are immutable in Python, which means you cannot change the existing string. But if you want to change any character in it, you could create a new string out it as follows,
def replace(s, position, character):
return s[:position] + character + s[position+1:]
replace('King', 1, 'o')
// result: Kong
Note: If you give the position value greater than the length of the string, it will append the character at the end.
replace('Dog', 10, 's')
// result: Dogs