MakeCodingSimple
July 7, 2023

How To Remove Character From String Using replace() in Python

Posted on July 7, 2023  (Last modified on July 11, 2023 )
2 minutes  • 391 words
Table of contents

How To Remove a Character from a string using replace() in python

Have you ever come across a situation where you needed to remove a specific character from a string in Python? In this tutorial we will learn about how to remove specific letters or characters from a string using the replace() function

When working with strings in Python, you might encounter scenarios where you need to eliminate a specific charecter from a string. Python offers various methods and functions that allow you to achieve this task efficiently. And now we will learn about the replace() function

Removing a spesific character

Python provides a built-in function called replace() that allows you to replace occurrences of a specific substring with another substring. In this case, we can replace the letter we want to remove with an empty string. For example:

name = "make coding simple"
newname =  name.replace('i', '')
print(newname)

Output:

make codng smple

In the example above, we replaced the letter i with an empty string to remove it.

Another example:

name = "make coding simple"
newname =  name.replace('make', '')
print(newname)

Output:

coding simple

In the example above, we removed an entire word. So it’s not only for a specific character or letter.

Removing Character in specific number of time

You also can remove letters for a specific number of times by passing a third argument in the replace() method. for example:

n = "okokok"
newn = n.replace('o', '', 2)
print(newn)

Output:

kkok

Remember that you use any character other than empty string to replace it with something you want.

Removing Whitespaces

To remove whitespace characters from a string, you can use replace() to replace them with an empty string. Here’s an example:

name = "  make  coding simple  "
newname =  name.replace(' ', '')
print(newname)

Output:

makecodingsimple

Conclusion:

The replace() function in Python is a useful tool for removing specific characters or substrings from a string. By replacing the target character or substring with an empty string, you can effectively remove it. The replace() function is versatile and can handle removing individual characters, entire words, or whitespace from a string. It provides flexibility and convenience in various programming tasks.


Share

 

Other Tutorial

 

Read Previous Read Next
How To Remove A Duplicate From A List In Python -
Find Me in Social Media

Join our social media community and be part of the conversation! Follow us for inspiring content.