PythonPython StringsPython case conversion
How do you convert a string to uppercase or lowercase?
Question 68 of 88 · Updated
On this page
- 1. Basic uppercase and lowercase conversion
- 2. Unicode casing is more than ASCII letter substitution
- 3. lower() versus casefold()
- 4. Combining normalization with case folding
- 5. Checking case with isupper() and islower()
- 6. Related transformations
- 7. Practical example: validate an ASCII status field
- 8. str casing versus bytes casing
- 9. Complexity, storage and testing
- 10. Common mistakes
- Interview-ready answer
- Official references
Use text.upper() to obtain uppercase text and text.lower() to obtain lowercase text. Both methods return a string result without changing the original string. For Unicode-aware caseless comparison, prefer text.casefold() when that is the intended comparison policy.
1. Basic uppercase and lowercase conversion#
PYTHONtext = 'PyThOn 123!' print(text.upper()) print(text.lower()) print(text)
Output:
PYTHON 123!
python 123!
PyThOn 123!The upper method applies Unicode uppercase mappings, while lower applies lowercase mappings. Digits and punctuation without case mappings remain unchanged.
Strings are immutable. Calling text.upper() and discarding the result does not change text. Assign the returned value if the name should refer to the converted text.
text = text.upper()The methods require no arguments. An empty string remains empty. Neither method removes spaces or performs general text validation.
2. Unicode casing is more than ASCII letter substitution#
For English ASCII letters, case conversion appears to map each letter to exactly one other letter. Python str supports Unicode, whose casing rules are broader: some mappings expand a single code point into several, and some depend on surrounding text.
PYTHONword = 'Straße' print(word.upper(), len(word), len(word.upper())) print(ascii('İ'.lower())) print('ΟΣ'.lower(), 'ΟΣΑ'.lower())
Output:
STRASSE 6 7
'i\u0307'
ος οσαThe German lowercase sharp s (U+00DF) becomes SS when uppercased. The uppercase dotted I (U+0130) lowercases to i followed by a combining dot above. The Greek capital sigma becomes final sigma at the end of the first word, but ordinary lowercase sigma in the second word.
These examples demonstrate three important properties:
- Case conversion can change the number of code points.
- The result may contain combining characters.
- Some mappings depend on surrounding characters.
Do not implement general Unicode casing by adding or subtracting 32 from every code point, or by independently converting each character and joining the results. Independent per-character processing can miss contextual mappings.
Python's built-in str casing methods use Unicode default casing rules, not a caller-specified language or locale. For example, Turkish-language display rules for dotted and dotless I may require a locale-aware text-processing library. Exact Unicode mappings can also depend on the Unicode database version used by the interpreter.
3. lower() versus casefold()#
Lowercase conversion and caseless comparison have different goals. The casefold method applies more aggressive Unicode mappings intended to remove case distinctions.
PYTHONa = 'Straße' b = 'STRASSE' print(a.lower() == b.lower()) print(a.casefold() == b.casefold()) print('ß'.upper().lower() == 'ß')
Output:
False
True
FalseLowercasing preserves the difference between ß and ss in this example. Case folding maps both values to matching sequences. The final comparison demonstrates that uppercase and lowercase operations are not necessarily inverses.
| Method | Primary purpose |
|---|---|
| upper() | Obtain uppercase text |
| lower() | Obtain lowercase text |
| casefold() | Produce a key for default Unicode caseless matching |
Casefold was introduced in Python 3.3. It is not a general solution for accent-insensitive search, locale-specific collation, visual similarity or identifier security. Choose the comparison policy according to the domain.
4. Combining normalization with case folding#
Unicode text can have canonically equivalent representations with different code-point sequences. Case folding alone does not guarantee that all canonically equivalent representations produce equal keys.
For canonical caseless matching, normalize to NFD, apply case folding, and normalize the result to NFD again.
PYTHONfrom unicodedata import normalize def canonical_key(text): return normalize('NFD', normalize('NFD', text).casefold()) print(canonical_key('CAFÉ') == canonical_key('cafe\u0301')) print(canonical_key('café') == canonical_key('cafe'))
Output:
True
FalseThe first comparison matches precomposed and decomposed accented text despite differences in case. The second remains false: the accent is not removed by canonical normalization or case folding.
The canonical caseless key is a comparison representation, not a recommended display representation. Retain original text when presentation, attribution or exact sequence preservation matters.
For persistent lookup keys, explicitly define the algorithm, Unicode version compatibility, migration procedure and collision policy. Distinct original strings can produce the same transformed key.
Do not apply this algorithm automatically to passwords, signed data, opaque tokens or identifiers whose specifications require exact matching. Unicode case folding and normalization do not detect every visually confusable character.
5. Checking case with isupper() and islower()#
The methods isupper and islower are predicates, not transformations. Each requires at least one cased character. Every cased character must have the requested case; characters without case do not invalidate the predicate.
PYTHONfor text in ['ABC123', 'abc!', '123', '', '中文', 'AbC']: print(repr(text), text.isupper(), text.islower())
Output:
'ABC123' True False
'abc!' False True
'123' False False
'' False False
'中文' False False
'AbC' False FalseA string containing only digits or uncased Chinese characters is neither uppercase nor lowercase according to these predicates. Therefore checking text == text.upper() is not equivalent to text.isupper(): an empty string, for example, equals its uppercase result but has no cased character.
Unicode titlecase characters also make the distinction between casing transformations and predicates relevant. Do not use isupper or islower as a replacement for a requirement such as "ASCII letters only."
6. Related transformations#
PYTHONtext = 'hELLO wORLD' print(text.capitalize()) print(text.title()) print(text.swapcase()) print("they're ready".title())
Output:
Hello world
Hello World
Hello World
They'Re ReadyThe capitalize method titlecases the first character and lowercases the rest. The title method applies title casing based on Python's notion of word boundaries. The swapcase method swaps uppercase and lowercase mappings where applicable.
The apostrophe example illustrates that title() is not a natural-language title editor. Its word-boundary rules may produce undesirable capitalization for contractions, names and language-specific conventions.
Also, applying swapcase twice is not guaranteed to recover the original Unicode string. Case mappings can be many-to-one or change length.
7. Practical example: validate an ASCII status field#
Suppose an API accepts one of three ASCII status labels, with case-insensitive spelling but no additional whitespace or non-ASCII lookalikes.
PYTHONdef parse_status(value): if not isinstance(value, str): raise TypeError('expected text') if not value.isascii(): raise ValueError('expected ASCII status') key = value.lower() if key not in {'ready', 'busy', 'offline'}: raise ValueError('unknown status') return key print(parse_status('READY')) try: parse_status('unknown') except ValueError as exc: print(exc)
Output:
ready
unknown statusThe validation policy deliberately requires ASCII before applying lower. This prevents accepting unintended Unicode equivalents in a protocol whose vocabulary is defined using ASCII.
The resulting lowercase value can be used for predictable membership checks or dispatch. Invalid types, non-ASCII labels and labels containing extra spaces are rejected. If whitespace should instead be accepted, define and test that policy explicitly rather than adding strip indiscriminately.
For a human-language search feature, this ASCII restriction would often be inappropriate. Input validation and text comparison policies should reflect the actual requirements.
8. str casing versus bytes casing#
PYTHONprint(b'caf\xc3\xa9'.upper()) print('café'.upper().encode('utf-8'))
Output:
b'CAF\xc3\xa9'
b'CAF\xc3\x89'Bytes.upper and bytes.lower operate on ASCII byte values, not decoded Unicode characters. In the first result the UTF-8 bytes representing é remain unchanged. In the second result the Unicode string is uppercased before being encoded, so the encoded text contains É.
When working with encoded text, decode according to the known encoding, apply the relevant Unicode transformation and encode again if a binary representation is required. Avoid changing arbitrary binary data as though it were text.
9. Complexity, storage and testing#
For ordinary CPython strings, let n be the number of input code points and m the number of resulting code points. Casing methods generally require work proportional to the text processed and produced, conventionally O(n + m), with output storage proportional to m when a result must be materialized. The exact allocation and internal representation depend on the implementation.
The Unicode mappings for a fixed Unicode version have bounded expansion, so a linear-time model in the input length is generally reasonable for these methods. This does not imply that input and output lengths are identical. The canonical-key example additionally performs normalization, whose processing costs depend on the sequence and normalization implementation.
For repeated comparisons against a large collection, precomputing appropriate keys can avoid redundant casing operations. This trades memory and preprocessing time for faster later comparisons. Keep original values for display and handle collisions according to the application's policy.
Test representative ASCII labels, mixed-case Unicode text, characters with expanding mappings, combining sequences, empty strings and uncased text. The local verification included 500 seeded ASCII inputs compared against independent explicit ASCII mapping rules for both uppercase and lowercase conversion.
10. Common mistakes#
| Mistake | Better approach |
|---|---|
| Ignoring the return value of upper() or lower() | Use the returned string |
| Using lower() as a universal Unicode caseless key | Select casefold and normalization as required |
| Assuming conversion preserves length | Account for expansion and output size |
| Assuming upper().lower() restores the original | Retain the original when exact preservation matters |
| Using isupper() to validate all characters as ASCII uppercase letters | Validate the actual allowed alphabet |
| Uppercasing UTF-8 bytes to uppercase Unicode text | Decode, transform and encode appropriately |
| Assuming casing is language-specific | Use an appropriate locale-aware mechanism when needed |
Interview-ready answer#
Python converts strings to uppercase and lowercase using str.upper() and str.lower(). The methods return string results without modifying the original immutable string. For default Unicode caseless matching, str.casefold() is more aggressive than lower(); canonical caseless matching additionally uses normalization. Unicode case conversion may change length or depend on context, so it is not always reversible or equivalent to ASCII character substitution. The isupper() and islower() predicates test case rather than converting text and require at least one cased character. Choose transformations according to the comparison, presentation and validation requirements.
Official references#
- Python Standard Library — str.upper
- Python Standard Library — str.lower
- Python Standard Library — str.casefold
- Python Standard Library — str.isupper
- Python Standard Library — str.islower
- Python Unicode HOWTO
- Python Standard Library — unicodedata
- Unicode Standard — Core Specification, Chapter 3: Conformance
Verification note: Eight runnable Python example groups matched their expected outputs on CPython 3.13.5 with Unicode database 15.1.0. Three additional expected-exception checks passed for the ASCII status parser. A seeded suite of 500 randomized ASCII inputs passed 1,000 independent casing assertions. Locale-specific libraries and other Python versions were not tested. The fenced Mermaid diagram was manually reviewed; local Mermaid parser/CLI and public-site rendering were unavailable. Official references are supplied under the authorized offline research exception; live documentation and the Supabase changelog were not checked.
References
- 1.Python Standard Library — str.upperdocs.python.org
- 2.Python Unicode HOWTOdocs.python.org
- 3.Python Standard Library — unicodedatadocs.python.org
- 4.
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design