Python Glossary Русский

all Python 3stringfunction

string.capwords()

functions

Splits a string on whitespace, capitalizes every word and joins it back together. Like title(), but it also collapses extra whitespace.

Syntax

string.capwords(s, sep=None)

capwords runs capitalize() on every word, and capitalize() lowercases the rest of the word: 'McDonald' comes back as 'Mcdonald' and 'USA' as 'Usa'. Unlike str.title(), it splits on whitespace rather than at every non-letter, so "it's" stays It's instead of becoming It'S — but with sep=None any run of whitespace (tabs, newlines included) collapses to a single space, so the original spacing is lost.

Examples

import string
print(string.capwords('hello world'))  # → Hello World
print(string.capwords('  hello   world  '))  # → Hello World — пробелы схлопываются
print(string.capwords("it's a test"))  # → It's A Test — в отличие от str.title(): It'S A Test
print(string.capwords('one,two,three', ','))  # → One,Two,Three
print(string.capwords('UPPER lower'))  # → Upper Lower

See also

Open in the full glossarydocs.python.orgReport an inaccuracy