Use Python built-in replace() function to replace the first character in the string. The str.replace takes 3 parameters old, new, and count (optional).
Where count indicates the number of times you want to replace the old substring with the new substring.
str.replace(old, new[, count])
Example replace the first character in a string Python
Simple example code using replace() function to returns a copy of the string with all occurrences of substring old replaced by new.
s = "Hello World!" res = s.replace("H", "X", 1) print(res)
If you don’t want to use
str.replace(), you can manually do it by taking advantage of splicing
s = "Hello World!" def rep(s, char, index): return s[:index] + char + s[index + 1:] # Test res = rep(s, "Z", 0) print(res)
Output: Zello World!
How to change character in string Python. Use the list() and join the funciton.
s = "Hello World!" new = list(s) new = 'Y' print(''.join(new))
Output: Yello World!
Do comment if you have any doubts and suggestions on this Python string topic.
Note: IDE: PyCharm 2021.1.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.