English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The program removes all punctuation from the string. We will use a for loop to check each character of the string. If the character is a punctuation, we assign an empty string to it.
To understand this example, you should understand the followingPython programmingTopic:
Sometimes, we may want to split a sentence into a list of words.
In this case, we may first need to clean the string and remove all punctuation. Below is an example of how to accomplish this function.
# Define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' my_str = "Hello!!!, he said" ---and went. # Accept user input # 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 string without punctuation print(no_punct)
Output result
Hello he said and went
In this program, we first define a string of punctuation. Then, we use a for loop to iterate over the provided string.
In each iteration, we check if the character is a punctuation or if it uses membership testing. We have an empty string, and if it is not a punctuation, we add (concatenate) the character to it. Finally, we display the cleaned string.