Online Tutorials & Training Materials | STechies.com
Register Login

How to Remove Punctuation from a String in Python?

12 Nov 2019 12:42 pm || 0

Strip Punctuation Python

Punctuations are symbols or sign which is used to indicates the structure of syntax. It is also known as separators. following are the examples of the punctuation used in programming:

  • ( ) - to represents arguments for a method.
  • [ ] - to represents array indices.
  • { } - to represents block of statements.
  • , - It is used to separate items in sets/lists.
  • ; - It is used to terminates statements and declarations of fields.

Using str.translate() Method

This is a fast method to remove all punctuation from a string.

In the following example, we will use the translate() function from the built-in string library to remove all punctuation from the string.

Example:

# Python program to strip punctuation from string
# Using string library

import string

# String with punctuation's
my_string = "Hello!!!, This is ##STechies$$."

# Remove all punctuation
print(my_string.translate(str.maketrans('', '', string.punctuation)))

Output:

Hello This is STechies

Using Regular Expressions (REGEX) Method

By using regular expressions, we can remove punctuation from string with the help of a sub-string function and pattern.

r'[^\w\s]' : Pattern to select character and numbers.

Example:

# Python program to strip punctuation from string
# Using Regular Expressions (REGEX) 

import re

# String with punctuation's
string = "Hello!!!, $#@!*()&,.This is ##STechies$$."

final_string = re.sub(r'[^\w\s]','',string)

# Print final String
print('String with Punctuation: ', string)
print('String without Punctuation: ', final_string)


Output:

String with Punctuation:  Hello!!!, $#@!*()&,.This is ##STechies$$.
String without Punctuation:  Hello This is STechies

Custom Function Method

In this following example, we will create such program to check each character in the string by using for loop, if the character is punctuation, then it will replace by an empty string.

Example:

# Python program to strip punctuation from string

# Define punctuation
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# String with punctuation's
string = "Hello!!!, This is ##STechies$$."

# Initialize empty string
final_string = ''

# for loop to check each character in the string
for ch in string:
   if ch not in punctuation:
       final_string = final_string + ch
       
# Print final String
print('String with Punctuation: ', string)
print('String without Punctuation: ', final_string)

Output:

String with Punctuation:  Hello!!!, This is ##STechies$$.
String without Punctuation:  Hello This is STechies