Skip to content

Python replace the first character in string | Example code

  • by

Use the 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 return 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 characters in string Python. Use the list() and join the function.

s = "Hello World!"

new = list(s)
new[0] = 'Y'


Output: Yello World!

Or you can utilize string slicing and concatenation. Here’s an example:

def replace_first_character(string, new_character):
    if len(string) > 0:
        new_string = new_character + string[1:]
        return new_string
        return string

# Example usage
original_string = "hello world"
new_string = replace_first_character(original_string, "H")
print(new_string)  # Output: "Hello world"

Do comment if you have any doubts or 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 *