string.punctuation in Python

In this tutorial, we are going to learn about the string.punctuation constant in Python. The string.punctuation is a pre-defined string constant in Python's string module that contains all ASCII punctuation characters. We can use it for text processing, password generation, and data validation.

What is string.punctuation?

The string.punctuation constant contains all printable ASCII punctuation characters as a single string ?

import string

# Display the punctuation string
print("Punctuation characters:")
print(string.punctuation)
print(f"Total characters: {len(string.punctuation)}")
Punctuation characters:
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Total characters: 32

Practical Examples

Removing Punctuation from Text

Remove all punctuation marks from a sentence ?

import string

text = "Hello, World! How are you today?"
cleaned_text = ""

for char in text:
    if char not in string.punctuation:
        cleaned_text += char

print("Original:", text)
print("Cleaned:", cleaned_text)
Original: Hello, World! How are you today?
Cleaned: Hello World How are you today

Counting Punctuation Characters

Count how many punctuation marks exist in a text ?

import string

text = "Python is great! Isn't it amazing? Yes, absolutely!"
punct_count = sum(1 for char in text if char in string.punctuation)

print(f"Text: {text}")
print(f"Punctuation marks found: {punct_count}")
Text: Python is great! Isn't it amazing? Yes, absolutely!
Punctuation marks found: 5

Password Generation

Generate a random password using punctuation characters ?

import string
import random

def generate_password(length=8):
    characters = string.ascii_letters + string.digits + string.punctuation
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

# Generate a sample password
sample_password = generate_password(10)
print(f"Generated password: {sample_password}")
print(f"Contains punctuation: {any(char in string.punctuation for char in sample_password)}")
Generated password: K9@mP#x2!L
Contains punctuation: True

Common Use Cases

Use Case Description Example
Text Cleaning Remove punctuation from text Data preprocessing
Password Validation Check if password contains special characters Security requirements
Text Analysis Count or identify punctuation Natural language processing

Conclusion

The string.punctuation constant provides easy access to all ASCII punctuation characters. It's particularly useful for text processing, password generation, and input validation tasks.

Updated on: 2026-03-25T09:03:43+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements