Python str.upper() function


str.upper() Function in Python

The str.upper() function in Python is used to convert all lowercase letters in a string to uppercase. It leaves non-alphabetical characters (such as digits, punctuation, and spaces) unchanged.

Syntax:

string.upper()
  • string: The string that you want to convert to uppercase.

Example:

# Example 1: Convert a string to uppercase my_string = "hello, world!" uppercase_string = my_string.upper() print(uppercase_string) # Output: "HELLO, WORLD!"

In this example:

  • The string "hello, world!" is converted to "HELLO, WORLD!".
  • The function changes only the lowercase letters to uppercase, while punctuation and spaces remain unaffected.

Example with mixed case:

# Example 2: Mixed case string mixed_string = "Python is Fun!" uppercase_mixed = mixed_string.upper() print(uppercase_mixed) # Output: "PYTHON IS FUN!"

Here, the lowercase letters in "Python is Fun!" are converted to uppercase, while the uppercase letters and other characters remain unchanged.

Example with numbers and special characters:

# Example 3: String with numbers and special characters special_string = "123abc!@#" uppercase_special = special_string.upper() print(uppercase_special) # Output: "123ABC!@#"

In this case:

  • The digits (123) and special characters (!@#) are not affected.
  • The lowercase letters (abc) are converted to uppercase (ABC).

Key Points:

  • str.upper() only affects alphabetic characters and converts them to uppercase.
  • It does not modify the original string but returns a new string with the changes.
  • Non-alphabetic characters like numbers, punctuation, and whitespace remain unchanged.