Skip to content

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)



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)

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'


Output: Yello World!

Do comment if you have any doubts and suggestions on this Python string topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Your email address will not be published. Required fields are marked *

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