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 a easiest way to replace an nth character in string Python.

Example replace an nth character in 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

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 *