Skip to main content Brad's PyNotes

String Module

TL;DR

The string module provides string constants, Template class for simple substitution, and advanced formatting utilities for text processing.

Interesting!

The string.Template class provides a safer alternative to % formatting - it prevents code injection by not allowing arbitrary expressions!

String Constants

python code snippet start

import string

print(string.ascii_letters)    # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits)           # 0123456789
print(string.punctuation)     # !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.whitespace)      # ' \t\n\r\x0b\x0c'

# Useful for validation
def is_valid_identifier(text):
    return text[0] in string.ascii_letters and \
           all(c in string.ascii_letters + string.digits + '_' for c in text)

python code snippet end

Template Substitution

python code snippet start

from string import Template

# Simple substitution
t = Template('Hello $name, welcome to $place!')
result = t.substitute(name='Alice', place='Python')
print(result)  # Hello Alice, welcome to Python!

# Safe substitution (missing keys don't error)
t = Template('$greeting $name')
result = t.safe_substitute(greeting='Hi')
print(result)  # Hi $name

# Using dictionary
data = {'user': 'Bob', 'action': 'login'}
t = Template('User $user performed $action')
print(t.substitute(data))  # User Bob performed login

python code snippet end

Custom Formatting

python code snippet start

# Advanced formatting with Formatter
from string import Formatter

class CustomFormatter(Formatter):
    def format_field(self, value, format_spec):
        if format_spec == 'upper':
            return str(value).upper()
        return super().format_field(value, format_spec)

formatter = CustomFormatter()
result = formatter.format('Hello {name:upper}!', name='world')
print(result)  # Hello WORLD!

python code snippet end

String Utilities

python code snippet start

# Capitalize words
text = 'hello world python'
print(string.capwords(text))  # Hello World Python

# Custom word separator
text = 'hello-world-python'
print(string.capwords(text, '-'))  # Hello-World-Python

python code snippet end

Practical Applications

python code snippet start

# Generate random strings
import random
import string

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

# Template for configuration files
config_template = Template("""
[database]
host = $db_host
port = $db_port
user = $db_user
""")

config = config_template.substitute(
    db_host='localhost',
    db_port=5432,
    db_user='admin'
)

python code snippet end

The string module bridges the gap between basic string operations and complex formatting needs - perfect for templates, validation, and text processing!

String templates provide a safer alternative to f-strings for user-controlled input, and work well with file I/O operations for configuration management.

Reference: string — Common string operations