Skip to content

Changing a character in a string Python | Example code

  • by

Use the 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")

print(res)

Output:

Changing a character in a string Python

Using slicing and concatenation:

s = "Hello, world!"
index_to_change = 7
new_character = 'W'

modified_string = s[:index_to_change] + new_character + s[index_to_change + 1:]
print(modified_string)

Converting the string to a list, modifying the list, and then converting it back to a string:

s= "Hello, world!"
index_to_change = 7
new_character = 'W'

string_list = list(s)
string_list[index_to_change] = new_character
modified_string = ''.join(string_list)
print(modified_string)

Remember that strings are immutable, so each of these methods creates a new string with the desired change rather than modifying the original string directly.

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)

print(res)

Output: abc

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 *