capwords Capitalizes Real Word Boundaries

Use string.capwords when str.title breaks words at apostrophes and hyphens: whitespace is the split unit, so contractions render correctly.

PythonCli Tooling

Code

pythonsnippet
16 lines
from string import capwords

# str.title 按非字母字符断词:撇号会把 don't 变成 Don'T
print('title   :', "don't stop".title())
print('capwords:', capwords("don't stop"))

# 连字符同样被 title 当成词界
print('title   :', 'state-of-the-art'.title())
print('capwords:', capwords('state-of-the-art'))

# capwords 先按空白切分、每词 capitalize:多余空白被压掉
print('collapse:', capwords('  hello   WORLD  '))

# 下划线:title 对非字母照样断词,capwords 保住词内小写
print('title   :', 'v2_beta release'.title())
print('capwords:', capwords('v2_beta release'))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

title   : Don'T Stop
capwords: Don't Stop
title   : State-Of-The-Art
capwords: State-of-the-art
collapse: Hello World
title   : V2_Beta Release
capwords: V2_beta Release

Using it

The demo output is labeled (title :, capwords:, collapse:), so every printed line traces back to the call that emitted it.

str.title treats every non-letter as a word boundary, which is why don't becomes Don'T and state-of-the-art capitalizes each hyphenated piece. capwords splits on whitespace and calls capitalize per word instead, so Don't Stop and state-of-the-art come out correctly, the extra whitespace in ' hello WORLD ' collapses to single spaces, and v2_beta keeps its lowercase tail.

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `string`.