removing punctuation from string python code example

Example 1: remove punctuation from string python

#with re
import re
s = "string. With. Punctuation?"
s = re.sub(r'[^\w\s]','',s)
#without re
s = "string. With. Punctuation?"
s.translate(str.maketrans('', '', string.punctuation))

Example 2: can you edit string.punctuation

>>> from string import punctuation
>>> from re import sub
>>> 
>>> string = "\Fred-Daniels!"
>>> translator = str.maketrans('','', sub('\-', '', punctuation))
>>> string
'\\Fred-Daniels!'
>>> string = string.translate(translator)
>>> string
'Fred-Daniels'

Example 3: clean punctuation from string python

s.translate(str.maketrans('', '', string.punctuation))

Example 4: remove punctuations using python

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

my_str = "Hello!!!, he said ---and went."

# To take input from the user
# my_str = input("Enter a string: ")

# remove punctuation from the string
no_punct = ""
for char in my_str:
   if char not in punctuations:
       no_punct = no_punct + char

# display the unpunctuated string
print(no_punct)

Example 5: python3 strip punctuation from string

import string
#make translator object
translator=str.maketrans('','',string.punctuation)
string_name=string_name.translate(translator)