Online Tutorials & Training Materials | STechies.com
Register Login

How to Remove Punctuation from a String in Python

|| 0

How to Remove Punctuation from a String in Python
Stechies

Punctuation are basically symbols or sign which is used to indicates the structure of a syntax, it is also know 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 very swift method to remove all punctuation from string.

In the following example we will use the translate() function from string built-in library to remove all punctuation from 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 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 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