2 Easy Ways To Remove Punctuation From Python Strings With Examples

Hello, readers! In this article, we will be focusing on the ways to remove punctuation from a Python string.

So, let us begin!!

Before diving deep into the concept of removal of punctuation marks, let us first understand the situations wherein we need to eliminate the punctuation marks.

When it comes to fetching the data values from APIs or web scraping, we often come across the data values in the JSON files which contain alphanumeric strings as well as punctuation marks. This makes the entire string seem to be a bit unformatted.

This is when we feel the need to eliminate or remove the punctuation marks from the string.

Let us now have a look at the different ways to remove the punctuation marks from the String.


1. Remove punctuation using regex library

Python provides us with regex library to deal with all kinds of regular expressions and manipulate the same.

We need to import the below library in order to work with regular expressionโ€“

We will be using re.sub(pattern, replacement, original_string) to remove the punctuation marks.

  • pattern: The punctuation marks or the pattern of expressions we want to replace.
  • replacement: The string to be placed as a replacement for the pattern.

Example:

Further, we have used re.sub() method to replace the punctuation marks with the replacement provided as โ€˜ โ€˜ i.e. a white space.

Output:


2. Using a Python for loop to eliminate punctuation marks

Python for loops can also be used to remove punctuation marks from a string as shown below:

  • Store all the punctuation characters in a string.
  • Create a for loop and build an if statement for every iteration such that if it detects a presence of a punctuation character, that would be replaced by a white space.

Let us try to understand the above method through an example.

Example:

Output:


Conclusion

By this, we have come to the end of this topic. Feel free to comment below, in case you come across any question.

For more such posts related to Python, stay tuned @ Python with JournalDev, and till then, Happy Learning!! ๐Ÿ™‚

By admin

Leave a Reply