Skip to content
Related Articles

Related Articles

Python | Print Alphabets till N

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 25 Jun, 2022

Sometimes, while working with Python, we can have a problem in which we need to print the specific number of alphabets in order. This can have application in school-level programming. Let’s discuss certain ways in which this problem can be solved. 

Method #1 : Using loop + chr()

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(). 

Python3




# Python3 code to demonstrate working of
# Print Alphabets till N
# Using loop
 
# initialize N
N = 20
 
# printing N
print("Number of elements required : " + str(N))
 
# Print Alphabets till N
# Using loop
res = ""
for idx in range(97, 97 + N):
       res = res + chr(idx)
     
# printing result
print("Alphabets till N are : " + str(res))

Output : 

Number of elements required : 20
Alphabets till N are : abcdefghijklmnopqrst

Method #2: Using string.ascii_lowercase + slicing:

Combination of the above functionalities can also be used to perform this task. In this, we use an inbuilt function to get extract the lowercase string and extract the N characters using slicing. 

Python3




# Python3 code to demonstrate working of
# Print Alphabets till N
# Using string.ascii_lowercase + slicing
import string
 
# initialize N
N = 20
 
# printing N
print(& quot
       Number of elements required : & quot
       + str(N))
 
# Print Alphabets till N
# Using string.ascii_lowercase + slicing
res = string.ascii_lowercase[:N]
 
# printing result
print(& quot
       Alphabets till N are : & quot
       + str(res))

Output : 

Number of elements required : 20
Alphabets till N are : abcdefghijklmnopqrst

Method #3 : Using ord() and chr() functions

The Python ord() function converts a character into an integer that represents the Unicode code of the character. Similarly, the chr() function converts a Unicode code character into the corresponding string.

Python3




# Python3 code to demonstrate working of
# Print Alphabets till N
# Using loop
 
# initialize N
N = 20
 
# printing N
print("Number of elements required : " + str(N))
 
# Print Alphabets till N
# Using loop
s=""
x=ord('a')+N-1
y=ord('a')
while(y<=x):
    s+=chr(y)
    y+=1
     
# printing result
print("Alphabets till N are : " + s)

Output

Number of elements required : 20
Alphabets till N are : abcdefghijklmnopqrst


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!