Open In App

Print Alphabets till N-Python

Last Updated : 07 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Printing Alphabets till N in Python involves generating a sequence of uppercase or lowercase letters starting from 'A' (or 'a') up to the N-th letter of the alphabet. For example, if N = 5, the output should be: 'A B C D E'. Let's explore a few ways to implement this in a clean and Pythonic way.

Using string.ascii_lowercase

We can easily print the first N alphabets using the string module's ascii_lowercase constant which contains all lowercase letters. By slicing this string we can extract the first N characters efficiently.

Python
import string

N = 20  
res = string.ascii_lowercase[:N]

print(res)

Output
abcdefghijklmnopqrst

Explanation: string.ascii_lowercase[:N] extracts the first 20 letters from the lowercase alphabet string.

Using map()

map() function with chr() converts a range of numbers into their corresponding alphabet characters, starting from 97 (ASCII value of 'a'). By mapping chr() over the range and joining the results we can efficiently print the first N alphabets.

Python
N = 20

res = ''.join(map(chr, range(97, 97 + N)))

print(res)

Output
abcdefghijklmnopqrst

Explanation: ''.join(map(chr, range(97, 97 + N))) generates the first 20 lowercase letters by converting ASCII values (starting from 97, which is 'a') to characters and joining them into a single string.

Using loop

This is brute force way to perform this task. In this, we iterate the elements till which we need to print and concatenate the strings accordingly after conversion to the character using chr()

Python
N = 20
res = ""

for i in range(N):
    res += chr(97 + i)
    
print(res)

Output
abcdefghijklmnopqrst

Explanation: We initialize an empty string res and then use a for loop to go from 0 to N-1. In each iteration, we convert the current index + 97 to a character using chr() and concatenate it to res.

Using List Comprehension

By iterating through a range of numbers, calculating the ASCII value for each letter. chr() function converts these numbers into their corresponding alphabet characters, starting from 97 for 'a'. After iterating and generating the list of characters, we can join them into a single string.

Python
N = 20

res= ''.join([chr(97 + i) for i in range(N)])

print(res)

Output
abcdefghijklmnopqrst

Explanation: This code generates the first 20 lowercase letters by creating a list of characters from ASCII values 97 ('a') to 116 ('t'), then joins them into a single string.


Next Article
Practice Tags :

Similar Reads