learn python string upper() with 5 example

The upper() method in Python is a built-in method that returns a copy of the original string with all the alphabetical characters converted to uppercase.

Here’s an example of how to use the upper() method in Python:

string = "hello, world!"
print(string.upper())

Example 1

Using upper() method on a string variable.

string = "hello, world!"
uppercase_string = string.upper()
print(uppercase_string)

Output:

HELLO, WORLD!

Example 2

Using upper() method on a string input by user.

string = input("Enter a string: ")
uppercase_string = string.upper()
print("Uppercase string:", uppercase_string)

Output:

Enter a string: pleypot
Uppercase string: PLEYPOT

Example 3

Using upper() method to check if a string contains all uppercase letters.

string = "HELLO, WORLD!"
if string == string.upper():
    print("String contains all uppercase letters")
else:
    print("String does not contain all uppercase letters")

Output:

String contains all uppercase letters

Example 4

Using upper() method with string formatting.

name = "John"
age = 30
greeting = f"Hello, my name is {name.upper()} and I am {age} years old"
print(greeting)

Output:

Hello, my name is JOHN and I am 30 years old

Example 5

Using upper() method with list comprehension.

strings = ["apple", "banana", "cherry"]
uppercase_strings = [string.upper() for string in strings]
print(uppercase_strings)

Output:

['APPLE', 'BANANA', 'CHERRY']

Leave a Reply

Your email address will not be published. Required fields are marked *