Convert strings to uppercase or lowercase in Python
Use Python string case methods, choose casefold for Unicode-aware comparisons, and avoid surprising title-case and whitespace behavior.
Use text.upper() for uppercase and text.lower() for lowercase. Python strings are immutable: these methods return a string result without modifying the original object.
Choose a case conversion
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.lower()) # hello world
print(text.capitalize()) # Hello world
print(text.title()) # Hello World
print(text.swapcase()) # HELLO WORLD
capitalize() titlecases the first character and lowercases the rest. It does not search for the first letter after leading whitespace. title() applies its own word-boundary rules, which may not match the style you want for names, headings, or acronyms.
Compare text without case distinctions
For general Unicode caseless matching, casefold() is more thorough than lower():
print("Straße".casefold() == "STRASSE".casefold()) # True
The German sharp s folds to ss. This means case conversion can change string length. lower() is still useful when you specifically want lowercase text; it is not inherently wrong for a constrained ASCII comparison.
Case folding does not by itself resolve every Unicode normalization difference or implement every locale-specific naming rule. If your application compares identifiers or human names, define and test its normalization and matching policy explicitly.
Test the current case
print("ABC".isupper()) # True
print("abc".islower()) # True
print("ABC123".isupper()) # True
print("123".isupper()) # False
These predicates examine cased characters. Digits and punctuation do not invalidate an otherwise uppercase string, but at least one cased character must be present.
FAQ
Will capitalize() preserve an acronym? No. "hELLO API".capitalize() becomes "Hello api". Use a rule designed for your content if acronyms must remain intact.
Why does title() produce They'Re? Its word-boundary behavior treats the apostrophe as a separator. "they're".title() is therefore not a reliable editorial title-casing operation. Use domain-specific rules for polished human-language text.
Does calling swapcase() twice always restore the original? No. Unicode case mappings can expand characters or lose distinctions. Do not treat case conversion as reversible encoding.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan