In this tutorial, we will learn how to print all uppercase letters in Python. This can be helpful in various situations where you may need to process text data, such as text analysis, pattern recognition, or cryptography.
We’ll discuss two different ways to achieve this:
- Using the string.ascii_uppercase attribute.
- Using a for loop and the chr() function.
Let’s dive in to see how to implement each of these methods in Python.
Step 1: Import the Required Module
The first method we’ll discuss involves utilizing the string module. This module provides various string manipulation functions and constants. To use its features, you need to import it into your Python script.
1 |
import string |
Step 2: Printing Uppercase Letters Using String Module
After importing the string module, you can access the ascii_uppercase attribute to print all uppercase letters. This attribute is a constant string containing all uppercase letters from A to Z.
1 2 3 |
import string print(string.ascii_uppercase) |
The output will be:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Step 3: Printing Uppercase Letters Using For Loop and Chr() Function
Another way to print all uppercase letters in Python is by using a for loop and the chr() function.
The chr() function returns a string representing a character whose Unicode code point is the integer passed as its argument. Uppercase letters have Unicode code points ranging from 65 to 90 (inclusive).
You can use the range() function along with a for loop to generate uppercase letters. Here is the code:
1 2 |
for i in range(65, 91): print(chr(i), end=' ') |
This will give you the same output as the previous method:
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Full Code
Here is the full code for both methods discussed in this tutorial:
1 2 3 4 5 6 7 8 |
import string # Method 1 - Using string.ascii_uppercase print(string.ascii_uppercase) # Method 2 - Using for loop and chr() function for i in range(65, 91): print(chr(i), end=' ') |
The output for the full code will be:
ABCDEFGHIJKLMNOPQRSTUVWXYZ A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Conclusion
In this tutorial, we have learned two different ways to print all uppercase letters in Python. You can either use the string.ascii_uppercase attribute or a combination of a for loop and the chr() function. Both methods are efficient and yield the desired output, so you can choose the one that fits your needs best.