Skip to content

Changing a character in a string Python | Example code

  • by

Use Python string replace() function to change characters in a string. It will change all occurrences of a character old with the desired character new.

Example how to change a character in a string Python

Simple example code changing multiple occurrences of the character anywhere in the given string.

a_string = "axayza Hello"

res = a_string.replace("a", "T")



Changing a character in a string Python

How to change one character in a string in Python?

Answer: Use list indexing to modify the one character in a string in Python. After change use join(iterable) with the empty string “” as a string and the modified list as iterable to construct a modified string.

a_string = "zbc"

l = list(a_string)
l[0] = "a"
res = "".join(l)


Output: abc

Do comment if you have any doubts or suggestions on this Python char 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.