Remove punctuation symbols from string
The problem
Often a string with special characters like "this \"string\""
shall be used as input of another program
with all the special characters removed. A case of use could be for example if the input string is to be used as
a filename in another program.
The solution
We create a translation table that maps any punctuation symbol into None
. Punctuation symbols in python are defined in the module string
.
import string
def remove_special_characters(input_string):
# Create a translation table mapping special characters to None
translation_table = str.maketrans("", "", string.punctuation)
# Remove special characters using the translation table
cleaned_string = input_string.translate(translation_table)
return cleaned_string
# Example usage
input_string = 'Hello! "How are you?"'
cleaned_string = remove_special_characters(input_string)
print(cleaned_string)