Python | Imprimir alfabetos hasta N

A veces, mientras trabajamos con Python, podemos tener un problema en el que necesitamos imprimir el número específico de alfabetos en orden. Esto puede tener aplicación en la programación a nivel escolar. Analicemos ciertas formas en que se puede resolver este problema. 

Método #1: Usar loop + chr()

Esta es una forma de fuerza bruta para realizar esta tarea. En esto, iteramos los elementos hasta los que necesitamos imprimir y concatenar las strings en consecuencia después de la conversión al carácter usando 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))
Producción : 

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

Método #2: Usando string.ascii_lowercase + corte:

La combinación de las funcionalidades anteriores también se puede utilizar para realizar esta tarea. En esto, usamos una función incorporada para extraer la string en minúsculas y extraer los N caracteres usando el corte. 

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))
Producción : 

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

Método #3: Usando las funciones ord() y chr()

La función Python ord() convierte un carácter en un número entero que representa el código Unicode del carácter. De manera similar, la función chr() convierte un carácter de código Unicode en la string correspondiente.

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)
Producción

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

Publicación traducida automáticamente

Artículo escrito por manjeet_04 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *