Python replace the first character in string | Example code

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)

Output:

Python replace the first character in string

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!

Another way

How to change character in string Python. Use the list() and join the funciton.

s = "Hello World!"

new = list(s)
new[0] = '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)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.