Skip to content

Replace an nth character in string Python | Example code

  • by

First, convert the string into a list, replace an nth character, and convert them back to a string. That’s the easiest way to replace an nth character in string Python.

Example replace an nth character in the string Python

Simple example code.

def replace(s, index, c):
    chars = list(s)
    chars[index] = c
    res = "".join(chars)
    return res


print(replace("House", 2, "r"))

Output:

Replace an nth character in string Python

Another example

def replace_nth_character(string, n, new_char):
    string_list = list(string)  # Convert string to list
    string_list[n - 1] = new_char  # Replace nth character (indexing starts at 0)
    new_string = ''.join(string_list)  # Convert list back to string
    return new_string

# Example usage
original_string = "Hello, World!"
n = 7
new_character = 'X'
modified_string = replace_nth_character(original_string, n, new_character)
print(modified_string)

It returns the modified string with the nth character replaced. Note that indexing starts at 0 in Python, so to replace the nth character, we subtract 1 from the provided index.

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

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading