string | Python Standard Library – Real Python
Skip to content

string

The Python string module provides a collection of string constants and utility functions for common string operations.

It includes predefined string constants, which can be particularly useful for tasks involving the classification and manipulation of characters.

Here’s a quick example:

Language: Python
>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

Key Features

  • Provides a set of string constants such as ascii_letters, digits, punctuation
  • Offers utility functions like capwords() for string manipulation
  • Facilitates character classification with constants like ascii_lowercase, whitespace

Frequently Used Classes and Functions

Examples

Capitalize the first letter of each word in a string:

Language: Python
>>> import string
>>> string.capwords("hello, world!")
'Hello, World!'

Check for ASCII letters:

Language: Python
>>> import string
>>> all(c in string.ascii_letters for c in "Python")
True

Common Use Cases

  • Generating random strings using predefined character sets
  • Formatting and manipulating text data
  • Validating and classifying characters in strings

Real-World Example

Suppose you need to generate a random string of a given length consisting of letters and digits. You can use the string module to easily access the necessary character sets:

Language: Python
>>> import string, random

>>> def random_string(length=8):
...     characters = string.ascii_letters + string.digits
...     return "".join(random.choices(characters, k=length))
...

>>> random_string()
'3hJ5kL8P'

In this example, you use the string module to construct a pool of characters and generate a random string.

Tutorial

Strings and Character Data in Python

In this tutorial, you'll learn how to use Python's rich set of operators and functions for working with strings. You'll cover the basics of creating strings using literals and the str() function, applying string methods, using operators and built-in functions with strings, and more!

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 18, 2025