Python Reference Β· String Methods
Python str.capitalize() method
Reference for Python str.capitalize(): upper-case the first character and lower-case the rest, how it differs from title(), and why it never changes the original.
The str.capitalize() method returns a copy of a string in which the first character is converted to upper case and every other character is converted to lower case. It is meant for a single sentence or a single word, such as a name typed in all caps.
Strings are immutable, so the original is never changed. Characters that have no case, such as digits or punctuation, stay as they are.
print("python IS fun".capitalize()) # Python is fun
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input Β· what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
str.capitalize()
| Name | Description |
|---|---|
| (none) | The method takes no arguments. |
Return value: a new str.
Raises: nothing for a string. Calling it on a non-string, for example capitalize(5) through the class, raises TypeError.
Usage notes
- The rest is lower-cased.
"NASA".capitalize()gives"Nasa". If you only want to upper-case the first letter and keep the remainder untouched, writes[:1].upper() + s[1:]. - Only the first character counts. If the string starts with a space, quote or digit, nothing is capitalized, because that first character has no upper-case form. Strip the string first when needed.
- Not the same as
title().capitalize()handles one position;title()changes the first letter of every word, and its idea of a word breaks on apostrophes. - Unicode aware. Accented letters work (
"Γ©lan"becomes"Γlan"). A few characters map to a special "title case" form rather than plain upper case, so letters outside the Latin alphabet can behave surprisingly. Test the languages you support. - Returns a copy. Assign the result:
name = name.capitalize(). - Empty string returns an empty string.
- Version note. Before Python 3.8 the first character was converted to upper case instead of title case, which only matters for a handful of rare characters.