Python Tutorials

Python Programs

Python Remove Punctuation from a String


Python Remove Punctuation from a String

In this tutorial, we will learn how to remove punctuation from a string in Python. We will cover the basic concept of string manipulation and implement a function to perform the operation.


What is String Manipulation

String manipulation involves altering, parsing, and analyzing strings in various ways. Removing punctuation from a string is a common task in text processing and data cleaning.


Syntax

The syntax to remove punctuation from a string in Python is:

import string

def remove_punctuation(s):
    return s.translate(str.maketrans('', '', string.punctuation))


Removing punctuation from a string

We can create a function to remove punctuation from a given string using the translate method and the string module.

For example,

  1. Import the string module.
  2. Define a function named remove_punctuation that takes one parameter s.
  3. Use the translate method with str.maketrans('', '', string.punctuation) to remove all punctuation from the string.
  4. Return the cleaned string.
  5. Call the function with a sample string and print the result.

Python Program

import string

def remove_punctuation(s):
    return s.translate(str.maketrans('', '', string.punctuation))

# Sample string
sample_string = "Hello, world! Welcome to Python programming."

# Remove punctuation from the sample string
result = remove_punctuation(sample_string)

# Print the result
print('String without punctuation:', result)

Output

String without punctuation: Hello world Welcome to Python programming