To capitalize all words in a string in Python, you can use the built-in string method .upper()
. This method converts every character within the string to its uppercase equivalent.
Using the .upper()
Method
Python strings come with several useful methods for manipulating text. One of the most common tasks is changing the case of the characters within a string. According to the provided information, performing the .upper()
method on a string converts all of the characters to uppercase.
This means if you have a string like "hello world"
, applying .upper()
will result in "HELLO WORLD"
. While the term "capitalize all words" might sometimes imply capitalizing only the first letter of each word (often called title case, which uses a different method like .title()
), the .upper()
method effectively makes every single letter in every word uppercase.
How it Works
The .upper()
method is called directly on a string object. It then returns a new string where all alphabetic characters have been converted to uppercase. Non-alphabetic characters (like numbers, spaces, and punctuation) remain unchanged.
# Example using a string from the reference
s = "Whereof one cannot speak, thereof one must be silent."
# Apply the .upper() method
s_uppercase = s.upper()
# Print the result
print(s_uppercase)
Output:
WHEREOF ONE CANNOT SPEAK, THEREOF ONE MUST BE SILENT.
As you can see, every letter in the string is now in uppercase.
Key Points about .upper()
- Returns a New String: String methods in Python typically return a new string; they do not modify the original string in place.
- Affects All Letters: Converts all lowercase letters to uppercase.
- Ignores Non-Letters: Leaves numbers, symbols, and spaces as they are.
Contrast this with the .lower()
method, which, as the reference notes, converts all characters to lowercase.
Practical Applications
Using .upper()
is useful for various purposes, such as:
- Standardizing input data (e.g., ensuring all country codes are uppercase).
- Creating headings or prominent text in reports or outputs.
- Performing case-insensitive comparisons (though
.lower()
is often preferred for this).
In summary, to make every character in every word of a string uppercase in Python, the straightforward and standard approach is to use the .upper()
method.