Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Python Programs - String

Remove all punctuation from a string - Python Program

Example 1 :

import string text = "Hello, world!" clean = "".join(ch for ch in text if ch not in string.punctuation) print(clean)

Output

 
OUTPUT  :
Hello world

Example 2 :

import string def remove_punctuation(text): """ Removes all punctuation marks from a given string. Args: text (str): The input string containing punctuation. Returns: str: The string with all punctuation removed. """ no_punct_text = "" for char in text: if char not in string.punctuation: no_punct_text += char return no_punct_text # Sample usage sample_string = "Hello, world! Python is fun; isn't it?" cleaned_string = remove_punctuation(sample_string) print("Original string:", sample_string) print("Cleaned string:", cleaned_string)

Output

 
OUTPUT  :
Original string: Hello, world! Python is fun; isn't it?
Cleaned string: Hello world Python is fun isnt it

Explanation:

Import string module:

The import string statement imports the built-in string module, which provides access to a collection of string constants, including string.punctuation. This constant contains a string of all common punctuation characters.

remove_punctuation function:

  • This function takes a textstring as input.
  • It initializes an empty string no_punct_textto store the characters without punctuation.
  • It then iterates through each charin the input text.
  • Inside the loop, it checks if the current charis not present in punctuation.
  • If the character is not punctuation, it is appended to no_punct_text. 
  • Finally, the function returns the no_punct_text