What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Python Replace Character in String

  • Oct 06, 2021
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Shivali Bhadaniya
Python Replace Character in String

 

When it comes to data cleaning and text processing, replacing the string characters in python is a critical task. There might be some spelling issues, formatting issues with the garbage character that should be removed necessarily before processing the data further. In this article, we will refer to some common methods to replace characters over different types of strings in python but before that, let us get some basic idea of python strings in detail.

What is String in Python?

Strings in python is a sequence of Unicode characters wrapped around single or double-quotes. You can also use triple quotes when the string is multi-line. However, python does not have a character data type unlike any other programming language and therefore, a string with length 1 is considered to be a single character. Hence, strings are ordered collections of characters that are immutable in nature. This means that you cannot add, update or delete the string after it is created. If any operations are to be performed, a copy of an original string is created and updated accordingly. The below example shows the python string in detail.

For Example

a = "Compile With Favtutor"
print(a) 

 

Output

Compile With Favtutor

 

How to Replace a Character in a String in Python?

Below are 6 common methods used to replace the character in strings while programming in python. 

1) Using slicing method

Slicing is a method in python which allows you to access different parts of sequence data types like strings, lists, and tuples. Using slicing, you can return a range of characters by specifying the start index and end index separated by a colon and return the part of the string. Similarly, here you can choose the character to be replaced by the slicing method and simply replace it with the new character as shown in the below example:

For Example

str = 'favtutor'
index = 0
new_character = 'F'
str = str[:index] + new_character + str[index+1:]
print(str)

 

Output

Favtutor

 

2) Using replace() method

Python possesses many in-built functions to make programming easy and replace() method is one of them. replace() method helps to replace the occurrence of the given old character with the new character or substring. The method contains the parameters like old(a character that you wish to replace), new(a new character you would like to replace with), and count(a number of times you want to replace the character). Take a look at the below example for a better understanding of the method.

For Example

str = "Compile with favtutor"
result = str.replace("f", "F")
print(result)

 

Output

Compile with Favtutor

 

3) Using the list data structure 

In this approach, first, you have to convert the given string into a list data type and then replace the character at the given index with the new character. Later you have to join the list of characters together to form a result string again. Check out the below example explaining the working of this approach. 

For Example

str = 'favtutor'
index = 0
new_character = 'F'
temp = list(str) 
temp[index] = new_character
str = "".join(temp)
print(str)

 

Output

Favtutor

 

4) Replace multiple characters with the same character

You can replace multiple characters in the given string with the new character using the string indexes. For this approach, you can make use of for loop to iterate through a string and find the given indexes. Later, the slicing method is used to replace the old character with the new character and get the final output.

For Example

str = 'Python' 
indexes = [2, 4, 5] 
new_character = 'a' 
result = '' 
for i in indexes:
    str = str[:i] + new_character + str[i+1:] 
print(str)

 

Output

Pyahaa

 

Also, check this in-depth blog for how to replace multiple characters in a string in python.

5) Replace multiple characters with different characters

This approach is a slight modification of the above method where you can replace multiple characters with different characters at the same time. Just like the above example, you can make use of for loop to iterate through string characters and replace them using the slicing method. Take a look at the below example for a better understanding.

For Example

str = 'Python'
indexes = {2: 'a',
           4: 'b',
           5: 'c'}

result = ''

# Replace multiple characters with different replacement characters
for index, replacement in indexes.items():
    str = str[:index] + indexes[index] + str[index + 1:]

print(str)

 

Output

Pyahbc

 

6) Using regex module

Python regex module specifically handles text data to find substrings, replace strings, or any other task. You can import this module in the python program and replace the old character with a new one effectively. The method takes three parameters i.e. the pattern that needs to be replaced, the replacement string, and the original string in which the substring has to be replaced. Check out the below example to learn the working of the regex module:

For Example

import re
address = '211B Baker Street'
new_address = re.sub('Street', 'St.', address)
print(new_address)

 

Output

211B Baker St.

 

 

Conclusion

We covered many examples displaying different ways to replace the characters of the string in python. As the string is one of the most important data structures in python, sometimes it is necessary to modify them according to the need of the program. Hence, it is highly recommended to learn and understand all of the above methods to replace the characters of strings and make your programming skills faster and efficient.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Shivali Bhadaniya
I'm Shivali Bhadaniya, a computer engineer student and technical content writer, very enthusiastic to learn and explore new technologies and looking towards great opportunities. It is amazing for me to share my knowledge through my content to help curious minds.