EN
Python - replace first character in string
0
points
In this article, we would like to show you how to replace first character in string in Python.
Quick solution:
text = "ABC ABC ABC"
replacement = "X"
result = text.replace(text[0:1], replacement, 1)
print(result) # XBC ABC ABC
Â
Practical example using replace()
method
In this example, we use replace()
method to replace first character in the text
string.
We use the following syntax:
replace(old, new, count)
Where:
old
- is a substring to replace,new
- is the replacement,count
 (optional argument) - is the number of times we want to replace the specified substring. You need to set it to1
, so you won't replace anything but the first occurrence of the substring.
Practical example:
text = "ABC ABC ABC"
replacement = "X"
result = text.replace(text[0:1], replacement, 1)
print("Before: ", text) # ABC ABC ABC
print("After: ", result) # XBC ABC ABC
Output:
Before: ABC ABC ABC
After: XBC ABC ABC
Note:
If you don't set the
count
argument, by default thereplace()
method will replace all occurrences of theA
 letter (substring).Output:
Before: ABC ABC ABC After: XYC XBC XBC