Python str.upper() Method: Syntax and Examples

Converting a Python string to uppercase gives it an uppercase form. Python’s str.upper() method returns a copy of a string with its cased characters converted to uppercase.

I’ll show how to call str.upper() and what happens to the original string when you use the returned value.

TL;DR

Call str.upper() with empty parentheses to get a string whose cased characters are uppercase.

  • It returns a value and leaves the original string unchanged.
  • Digits, spaces, and punctuation remain as they are.
  • Unicode casing can change the number of characters.
  • Use isupper() to test case and casefold() for caseless comparisons.

What Is str.upper() in Python?

str.upper() returns a copy of a string with its cased characters converted to uppercase.

Call upper() on a str value. The returned value can supply uppercase display text.

message = "Have a nice day!"
uppercase_message = message.upper()
print(uppercase_message)
print(message)

How to Use str.upper() Step by Step

The steps below show how to display the result, assign it, and apply the method to a list.

Step 1: Start with a string value

Put the text you want to convert in a string variable. This example includes lowercase letters and spaces, so the output makes the changed letters clear.

text = "Have a nice day"

Step 2: Call upper() without arguments

Place a dot between the string value and the method call.

print(text.upper())

Step 3: Keep or replace the original value

The source value remains available for code that needs its original spelling.

uppercase_text = text.upper()
print(uppercase_text)
print(text)

I ran python3 upper_demo.py. The output includes the converted text, its source, a Unicode example, and case checks:

HAVE A NICE DAY
Have a nice day
STRASSE
False
True
False

The output separates the displayed conversion from the original. It also shows the Unicode result and the two Boolean checks.

Step 4: Convert each string in a collection

A list comprehension applies the conversion to each name and stores the results in a separate list.

names = ["Ada", "grace hopper"]
uppercase_names = [name.upper() for name in names]
print(uppercase_names)

Use the source list for its original labels and the result list for uppercase output.

Step 5: Standardize case for comparison

For a case-insensitive identifier, create a comparison form from each value and apply the same choice to incoming searches. A command keyword, product code, and display name can have different field requirements.

Values to compareCase-only resultOther rule to decide
“Admin” and “ADMIN”Same uppercase formWhether the field ignores case
“team name” and “teamname”Still differentWhether spaces matter
“item-7” and “item_7”Still differentWhether punctuation is interchangeable

Before storing keys in a dictionary, choose how the program should handle two source values that resolve to the same key. Apply the transformation when an input record is validated or a search key is prepared.

Case normalization is useful only when the field’s contract says capitalization does not distinguish values. A username field may follow that rule, while a password must preserve its exact characters. Decide the rule at the boundary where input enters the program, then use the same rule for saved records and later lookups.

A dictionary keyed by the converted form can merge inputs that were distinct before conversion. For example, “Admin” and “ADMIN” both produce the key “ADMIN”. If both records must remain separate, store an additional identifier or reject the duplicate instead of silently overwriting one value.

For a small lookup table, build keys with a comprehension and retain the original labels as values. That lets the program compare consistently while still displaying the spelling chosen for each record.

labels = ["Admin", "Guest"]
by_key = {label.upper(): label for label in labels}
query = "ADMIN"
print(by_key.get(query.upper()))

The lookup returns the retained label, “Admin”. If two labels normalize to the same key, the later dictionary entry replaces the earlier value, so define a duplicate policy before using this form for user data.

Use casefold() when the task is Unicode-aware caseless matching rather than producing uppercase display text. Unicode normalization handles a different question: whether canonically equivalent sequences should compare as equal.

The Python Unicode HOWTO demonstrates normalizing to NFD, applying casefold(), then normalizing again. Apply the same sequence to both operands and keep the original strings for display.

Before changing a comparison key in an existing application, test the proposed rule against representative records. Include pairs differing only in case and pairs with accents or compatibility characters if those can appear in the field. A rule that merges values may affect saved data, so review collisions before rebuilding an index.

Choose the representation based on the operation. Uppercase text suits a documented storage convention or a display request. A comparison key is internal and should not replace the value shown to a person unless the display rule calls for uppercase.

For identifiers, case conversion does not validate syntax. A value can become uppercase and still contain spaces or punctuation that the identifier format forbids. Validate the allowed characters and length separately, then normalize only after the format check succeeds.

Order matters when a program both trims and changes case. If the field specification ignores surrounding whitespace, strip that whitespace at the input boundary and then apply the case rule. Do not trim by habit: a space can be meaningful in a quoted phrase or a display label.

When records come from different systems, document which side owns the canonical spelling. A lookup may use a normalized key while preserving the source value in the record. That separation helps avoid changing what a user originally entered merely to make searches consistent.

A report can render the source spelling or a transformed label according to its display requirements. When later code slices the result, use positions that refer to the converted value rather than assuming its indices match the source.

For line-oriented data, decide whether the newline belongs to the value before converting it. upper() leaves whitespace in place, including tabs and line breaks. If a file-reading operation retains a line ending, remove it with the appropriate line-processing step rather than expecting case conversion to clean the record.

Applying the method to one field also leaves the surrounding data structure unchanged unless the program assigns a new value into it. A record can keep its original field and add a derived field for search or display. That choice makes it possible to inspect both forms when a comparison gives an unexpected result.

For a large iterable, a generator expression can yield converted values as the consumer requests them, while a list comprehension builds a list immediately. Select the form based on whether later code needs to revisit the results or only process them once. Neither option changes the source strings.

When a conversion is part of a data import, keep it near the boundary and make the resulting field name clear. A label such as normalized_name tells later code that it should use a derived value, while a field named name can remain the source value. Clear names reduce accidental display of a comparison form.

Testing a transformation means checking both representative inputs and the decisions that follow from the result. Include a value with no letters, a mixed-case value, and a value with any non-ASCII characters allowed by the input contract. Then verify that output formatting and lookup behavior match separate requirements.

Check the comparison rule

Check idempotence by confirming a converted value keeps the same uppercase form when converted again. When a matching policy changes, review the records affected before replacing stored keys.

Edge Cases and Related Methods

Unicode case mappings and uncased input create results that simple alphabetic examples do not show.

I checked the converted value and its length with this code:

I ran python3 upper_demo.py and saw straße become STRASSE, with its length changing from six to seven characters.

An empty value or a string of digits has no cased letter. Calling isupper() on either result returns False because the predicate needs at least one cased character.

I passed an argument in the probe and got TypeError: str.upper() takes no arguments (1 given). Remove the argument to fix it.

MethodPurposeExample
upper()Return uppercase text“Hello”.upper() gives “HELLO”
lower()Return lowercase text“Hello”.lower() gives “hello”
title()Capitalize words for display“hello world”.title() gives “Hello World”
isupper()Test whether cased letters are uppercase“HELLO”.isupper() gives True
casefold()Prepare text for caseless matching“Straße”.casefold() gives “strasse”

Choose accepted characters and format independently from the casing predicate.

Use a generator expression instead when values should be processed one at a time rather than stored as a list.

labels = ["PyThOn", "Java", "SQL"]
converted = [label.upper() for label in labels]
print(converted)

Whitespace keeps its position in the string. Trim leading or trailing spaces as a separate input step when the field’s rules permit it.

When a collection comes from a file or an API, check its element types before applying a string method. Converting every value to str() may hide malformed data, so validate the expected type at the input boundary.

For domain-specific sorting, the desired order may depend on language or product rules that a generic key does not express. A casefold-based key can guide case-insensitive ordering while stored identifiers keep their equality rules.

upper() accepts no arguments, so a locale or custom mapping cannot be passed to the method. If a product needs language-specific rules beyond Python’s string behavior, define that requirement explicitly and select an appropriate domain-specific implementation.

Python compares strings by their contents, so differently cased spellings remain distinct until transformed.

Input pairAfter case conversionDecision to make
“User” and “USER”Same uppercase keyWhether identifiers ignore case
“user name” and “username”Different keysWhether spaces are significant
“tag-a” and “tag_a”Different keysWhether separators are interchangeable

This table distinguishes case conversion from rules about spaces and punctuation.

Python’s string-method documentation shows that title() can produce an unexpected apostrophe form in a contraction. A title-style transformation can also alter acronyms or product spellings, so choose a display rule that fits the text rather than assuming title() preserves names.

Valueisupper() resultReason
“ABC!”TrueCased letters are uppercase, while punctuation is uncased
“!!!”FalseThe value has no cased letter
“AbC”FalseA cased letter remains lowercase

Use the Boolean result when code needs to branch on casing rather than text to display.

The Unicode HOWTO distinguishes canonical and compatibility normalization. NFC and NFD compose or decompose canonical sequences, while NFKC and NFKD also apply compatibility mappings. Pick a form only when the data contract says those sequences should compare as equivalent.

For caseless comparison across Unicode forms, Python’s Unicode HOWTO shows normalizing each operand to NFD, applying casefold(), and normalizing again before equality testing. Use that comparison form for matching, not as the text to display.

swapcase() serves another job: it switches the case of cased characters instead of choosing one canonical form. It is useful for demonstrating case changes, but it does not standardize mixed-case input for comparison.

Python distinguishes text from binary data. str.upper() operates on Unicode text, so decode bytes with the file’s actual encoding before using the method.

Bytes objects also provide an upper() method for byte data, using ASCII case conversion. If a program needs Unicode text casing, decode the data first, apply the text rule, and encode it again only when writing to a byte-oriented destination.

At a system boundary, check the value’s type and decoding contract before choosing a string operation, especially when non-ASCII characters are allowed.

Value formOperation contextReader check
strUnicode text casingConfirm the text-decoding boundary
bytesEncoded data operationsDecode before Unicode case handling

In a text-processing pipeline, keep the conversion steps visible: decode input, validate the expected text, apply the field’s casing rule, then encode only if the next interface requires bytes. This ordering makes it clear which stage handles representation and which stage changes letter case.

Conclusion

For more Python topics, see Python reserved words and how to check them and Python identifier rules. The Python documentation for string methods defines upper(), isupper(), and related behavior.

FAQ

These answers cover common questions about the method’s return value and use.

What does upper() do in Python?

It returns a copy of a string with cased characters converted to uppercase.

Does upper() change the original string?

No. Python strings are immutable, and upper() returns a string value. Assign the result if you want to keep it.

Why can upper().isupper() return False?

The result may contain no cased characters, as with digits or punctuation, so isupper() returns False.

Pankaj Kumar
Pankaj Kumar

I have been working on Python programming for more than 12 years. At AskPython, I share my learning on Python with other fellow developers.

Articles: 261