string
Updated March 13, 2026 · Modules
string constants formatting stdlib
The string module provides useful constants for character classification and a Formatter class for custom string formatting. Unlike string methods that operate on string instances, these are module-level utilities that help with common string tasks.
String Constants
The module defines several constants containing useful character sets. These are handy for validation, parsing, and character classification.
import string
# Check what each constant contains
print(string.ascii_letters)
# abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.ascii_lowercase)
# abcdefghijklmnopqrstuvwxyz
print(string.ascii_uppercase)
# ABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)
# 0123456789
print(string.hexdigits)
# 0123456789abcdefABCDEF
print(string.octdigits)
# 01234567
print(string.punctuation)
# !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.printable)
# 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.whitespace)
#
capwords()
The capwords() function capitalizes the first letter of each word in a string. It splits on whitespace, capitalizes each word, and joins them back.
Syntax
string.capwords(s, sep=None)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
s | str | — | The input string to process |
sep | str | None | Separator used to split words. Defaults to whitespace |
Examples
Basic usage
import string
result = string.capwords("hello world")
print(result)
# Hello World
Custom separator
import string
result = string.capwords("apple,banana,cherry", sep=",")
print(result)
# Apple,Banana,Cherry
Whitespace handling
import string
# Multiple spaces are treated as one split point
result = string.capwords(" multiple spaces ")
print(result)
# Multiple Spaces
Formatter Class
The Formatter class provides flexible string formatting. It implements the same format string syntax as the built-in str.format() method, but as a class you can subclass to customize behavior.
Syntax
class string.Formatter
Methods
| Method | Description |
|---|---|
format(format_string, *args, **kwargs) | Main API — formats the string with given arguments |
vformat(format_string, args, kwargs) | Does the actual work, useful when passing a dict |
parse(format_string) | Returns tuples of (literal_text, field_name, format_spec, conversion) |
get_field(field_name, args, kwargs) | Resolves a field name to its value |
get_value(key, args, kwargs) | Gets a positional or keyword argument by key |
Examples
Basic formatting
import string
f = string.Formatter()
result = f.format("{0} {1}", "Hello", "World")
print(result)
# Hello World
Parsing format strings
import string
f = string.Formatter()
# parse() breaks a format string into its components
result = list(f.parse("Hello {0}, your score is {1}!"))
print(result)
# [('Hello ', '0', '', None), (', your score is ', '1', '', None), ('!', '', '', None)]
Custom formatting
import string
class MyFormatter(string.Formatter):
def format_field(self, value, format_spec):
# Custom: add brackets around formatted values
return f"[{super().format_field(value, format_spec)}]"
f = MyFormatter()
result = f.format("{0:.2f}", 3.14159)
print(result)
# [3.14]
Common Patterns
Character class validation
import string
def is_ascii(s):
"""Check if string contains only ASCII characters."""
return all(c in string.printable for c in s)
print(is_ascii("Hello World")) # True
print(is_ascii("Héllo")) # False
print(is_ascii("123")) # True
Generating random strings
import random
import string
def generate_random_string(length=10, charset=string.ascii_letters):
"""Generate a random string from a character set."""
return ''.join(random.choice(charset) for _ in range(length))
# Random alphanumeric string
print(generate_random_string(8))
# kR4mTqNp
# Random lowercase + digits (like a password)
print(generate_random_string(12, string.ascii_lowercase + string.digits))
# a7b3c9d2e1f4
Text cleaning
import string
def remove_punctuation(text):
"""Remove punctuation from text."""
return text.translate(str.maketrans('', '', string.punctuation))
result = remove_punctuation("Hello, World! How are you?")
print(result)
# Hello World How are you