Fundamentals 7 min read

Master Python’s string Module: capwords, Template, and Performance Hacks

This article walks through Python’s string module, explaining how to import it, use the capwords function with custom implementations and performance benchmarks, and leverage the Template class for safe string substitution, including customization of delimiters and patterns.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Python’s string Module: capwords, Template, and Performance Hacks

Importing the module

import string

capwords

The capwords function capitalizes the first letter of each word in a string, optionally using a custom separator.

def capwords(s, sep=None):
    return (sep or ' ').join(x.capitalize() for x in s.split(sep))

Example usage:

>> s = 'my name is python'
>>> capwords(s)
'My Name Is Python'

>>> s = 'my-name-is-python'
>>> capwords(s, '-')
'My-Name-Is-Python'

Alternative implementations using map and methodcaller:

def capwords1(s: str, seq: str=None) -> str:
    return (seq or ' ').join(map(str.capitalize, s.split(seq)))

from operator import methodcaller

def capwords2(s: str, seq: str=None) -> str:
    return (seq or ' ').join(map(methodcaller('capitalize'), s.split(seq)))

Performance comparison (run in IPython) shows the first custom version is slightly faster than the built‑in implementation, while the second custom version is slower:

text = "your time is limted, so don't waste it living someone else's lives" * 10000
%timeit capwords(text)   # 24.9 ms
%timeit capwords1(text)  # 22.1 ms
%timeit capwords2(text)  # 28.4 ms

Template

The Template class provides safe string interpolation using $ placeholders.

from string import Template
string = '姓名:$name 年龄:${age} 爱好:$hobby'
template = Template(string)

Substitution with a dictionary:

template.substitute({'name':'Python','age':30,'hobby':'all'})
# '姓名:Python 年龄:30 爱好:all'

Keyword‑argument substitution raises KeyError if a placeholder is missing; safe_substitute leaves missing placeholders unchanged:

template.safe_substitute(name='Python', age=30, hobb='all')
# '姓名:Python 年龄:30 爱好:$hobby'

Key class attributes of Template:

class Template(metaclass=_TemplateMetaclass):
    """A string class for supporting $-substitutions."""
    delimiter = '$'
    idpattern = r'(?a:[_a-z][_a-z0-9]*)'
    braceidpattern = None
    flags = _re.IGNORECASE

Custom subclass can override delimiter and idpattern:

class MyTemplate(Template):
    delimiter = '%'
    idpattern = '[_][a-z]+_[a-z]+'

Using the custom template:

s = '%_name_main %age'
template = MyTemplate(s)
template.safe_substitute(_name_main='Python', age=30)
# 'Python %age'

These examples demonstrate how to work with the string module’s utilities, compare implementations, and safely perform string interpolation.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

performanceCode Exampletemplatestring-modulecapwords
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.