The string module in Python is a built-in module that provides a collection of string constants and utility functions for common string operations. It is part of the Python Standard Library and does not require external installation.

Key Features

String Constants

These predefined constants are useful for character classification and validation:

  • string.ascii_letters: Concatenation of ascii_lowercase and ascii_uppercase'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

  • string.ascii_lowercase: Lowercase ASCII letters → 'abcdefghijklmnopqrstuvwxyz'

  • string.ascii_uppercase: Uppercase ASCII letters → 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

  • string.digits: Decimal digits → '0123456789'

  • string.hexdigits: Hexadecimal digits → '0123456789abcdefABCDEF'

  • string.octdigits: Octal digits → '01234567'

  • string.punctuation: ASCII punctuation characters → '!"#$%&\'()*+,-./:;<=>?@[\\]^_{|}~'`

  • string.printable: All printable ASCII characters (digits, letters, punctuation, whitespace)

  • string.whitespace: All ASCII whitespace characters → ' \t\n\r\x0b\x0c'

Utility Functions

  • string.capwords(s, sep=None): Splits the string into words, capitalizes each word, and rejoins them. Useful for title formatting.

Classes

  • string.Formatter: Allows custom string formatting behavior, similar to str.format(). Useful for extending or modifying format string syntax.

  • string.Template: Provides simple string substitution using $ placeholders. Safer than str.format() for user-provided templates.

Example Usage

import string

# Check if characters are digits
text = "123abc"
print(all(c in string.digits for c in text))  # False

# Capitalize words
print(string.capwords("hello world"))  # "Hello World"

# Generate random string with letters and digits
import random
random_string = ''.join(random.choices(string.ascii_letters + string.digits, k=8))
print(random_string)  # e.g., "aB3kL9mX"

Note: Many string operations are now available as built-in string methods (e.g., str.upper(), str.split()), so the string module is primarily used for constants and advanced formatting features.

The string module contains a set of useful constants, such as ascii_letters and digits, and the module is often still imported for that reason.

Answer from Carl Younger on Stack Overflow
🌐
Python
docs.python.org › 3 › library › string.html
Common string operations — Python 3.14.3 documentation
Source code: Lib/string/__init__.py String constants: The constants defined in this module are: Custom string formatting: The built-in string class provides the ability to do complex variable subst...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string-module
Python String Module - GeeksforGeeks
July 23, 2025 - From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines various string operations that are commonly encountered in programming. Note: The Python String module is a part of the standard Python library, so we do not need to explicitly install it.
🌐
DigitalOcean
digitalocean.com › community › tutorials › python-string-module
Python String Module | DigitalOcean
August 3, 2022 - import string # string module constants ... 0123456789 0123456789abcdefABCDEF !"#$%&'()*+,-./:;?@[\]^_`{|}~ Python string module contains a single utility function - capwords(s, sep=None)....
🌐
W3Schools
w3schools.com › python › python_ref_string.asp
Python String Methods
Python has a set of built-in methods that you can use on strings.
🌐
W3Schools
w3schools.com › python › ref_module_string.asp
Python string Module
Use it to access predefined sets of characters (letters, digits, punctuation) or to create custom string formatters using the Template class. ... If you want to use W3Schools services as an educational institution, team or enterprise, send us ...
🌐
LaunchCode
education.launchcode.org › lchs › chapters › strings › string-module.html
7.10. The string Module — LaunchCode's LCHS documentation
We’ve talked before about string methods. The Python language gives us another means of working with string data. The Python string module provides several constants that are useful for checking to see if a character, slice, or string contains letters, digits, symbols, etc.
🌐
Real Python
realpython.com › ref › stdlib › string
string | Python Standard Library – Real Python
The Python string module provides a collection of string constants and utility functions for common string operations.
Find elsewhere
🌐
O'Reilly
oreilly.com › library › view › python-standard-library › 0596000960 › ch01s07.html
The string Module - Python Standard Library [Book]
May 10, 2001 - The string Module The string module contains a number of functions to process standard Python strings, as shown in Example 1-51.Example 1-51. Using the string ModuleFile:... - Selection from Python Standard Library [Book]
Author   Fredrik Lundh
Published   2001
Pages   304
🌐
Real Python
realpython.com › lessons › string-module
string Module (Video) – Real Python
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... In this lesson, you’ll learn about the string module. This module will help you quickly access some string constants.
Published   April 21, 2020
🌐
LaunchCode
education.launchcode.org › data-analysis › chapters › strings › string-module.html
8.10. The string Module — Data Analysis documentation
We’ve talked before about string methods. The Python language gives us another means of working with string data. The Python string module provides several constants that are useful for checking to see if a character, slice, or string contains letters, digits, symbols, etc.
🌐
Scaler
scaler.com › home › topics › python string module
Python String Module - Scaler Topics
December 19, 2022 - Breaking down the heading of this article - Python string module, let's talk about the module first. Some predefined code that performs certain tasks and can be used in other Python programs, by importing it, is called a module. The string here is, not the string class that you have read about.
🌐
Python Module of the Week
pymotw.com › 2 › string
string – Working with text - Python Module of the Week
The constants in the string module can be used to specify categories of characters such as ascii_letters and digits. Some of the constants, such as lowercase, are locale-dependent so the value changes to reflect the language settings of the user.
🌐
Hyperskill
hyperskill.org › learn › step › 15332
The string module
Hyperskill is an educational platform for learning programming and software development through project-based courses, that helps you secure a job in tech. Master Python, Java, Kotlin, and more with real-world coding challenges.
Top answer
1 of 6
62

Here is how to import a string as a module (Python 2.x):

Copyimport sys,imp

my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec my_code in mymodule.__dict__

In Python 3, exec is a function, so this should work:

Copyimport sys,imp

my_code = 'a = 5'
mymodule = imp.new_module('mymodule')
exec(my_code, mymodule.__dict__)

Now access the module attributes (and functions, classes etc) as:

Copyprint(mymodule.a)
>>> 5

To ignore any next attempt to import, add the module to sys:

Copysys.modules['mymodule'] = mymodule
2 of 6
35

imp.new_module is deprecated since python 3.4, but it still works as of python 3.9

imp.new_module was replaced with importlib.util.module_from_spec

importlib.util.module_from_spec is preferred over using types.ModuleType to create a new module as spec is used to set as many import-controlled attributes on the module as possible.

importlib.util.spec_from_loader uses available loader APIs, such as InspectLoader.is_package(), to fill in any missing information on the spec.

these module attributes are __builtins__ __doc__ __loader__ __name__ __package__ __spec__

Copy
import sys, importlib.util

def import_module_from_string(name: str, source: str):
  """
  Import module from source string.
  Example use:
  import_module_from_string("m", "f = lambda: print('hello')")
  m.f()
  """
  spec = importlib.util.spec_from_loader(name, loader=None)
  module = importlib.util.module_from_spec(spec)
  exec(source, module.__dict__)
  sys.modules[name] = module
  globals()[name] = module


# demo

# note: "if True:" allows to indent the source string
import_module_from_string('hello_module', '''if True:
  def hello():
    print('hello')
''')

hello_module.hello()
🌐
Pynerds
pynerds.com › the-string-module-in-python
The string module in Python
January 9, 2024 - The string module in the standard library provide various tools for working with strings. It contain several constants, functions, and classes to aid
🌐
Python.org
discuss.python.org › ideas
How about importing modules as strings - Ideas - Discussions on Python.org
April 9, 2022 - For example: import "a.py" import "E:/a/b.py" import ".a/b.py" This can import some modules that can’t be imported in the current method.
🌐
PyPI
pypi.org › project › strings
strings · PyPI
Python strings for humans. ... >>> from strings import string >>> s = string("Hello, World") >>> s 'Hello, World' >>> s.len() 12 >>> s.length 12 >>> s.size 12 >>> s + ", What?" Traceback (most recent call last): File "strings.py", line 27, in <module> x = s.add(", world") File "strings.py", line 20, in add return self + string(value) File "strings.py", line 23, in __add__ raise NotImplementedError("Use add instead") NotImplementedError: Use add instead >>> s.add(", What?") 'Hello, World, What?'
      » pip install strings
    
Published   Jul 11, 2013
Version   0.1.2
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-string
Python String - GeeksforGeeks
Example: In this example we are changing first character by building a new string. ... In Python, it is not possible to delete individual characters from a string since strings are immutable.
Published   2 weeks ago