logo

Alfabet en Python

En aquest tutorial, descobrireu les diferents funcions de Python que podeu utilitzar per crear una llista alfabètica. Aquestes funcions poden ser molt útils a l'hora de preparar-se per a concursos de programació o problemes d'entrevistes. Amb el mòdul de cadena Python, descobrireu com crear una llista de totes les lletres minúscules i majúscules de l'alfabet ASCII. També es cobreixen les implementacions bàsiques que depenen dels mètodes ord() i chr() integrats en Python.

Ús del mòdul String per fer una llista Python de l'alfabet

L'ús del mòdul de cadena Python és la manera més ràpida i natural de crear una llista de totes les lletres de l'alfabet. No cal instal·lar res perquè el mòdul de cadena de Python és membre de la biblioteca de Python per defecte. L'ús de les instàncies de les lletres string.ascii, string.ascii minúscules i string.ascii majúscules facilita la recuperació d'una llista de totes les lletres de l'alfabet.

Aquestes instàncies del mòdul de cadena retornen els alfabets minúscules i majúscules, tal com indiquen els seus noms, i els alfabets minúscules i majúscules adequats. Els valors són constants i independents de la configuració regional. Per tant, sempre proporcionen els mateixos resultats independentment de la configuració regional que especifiqueu.

Fem una ullada a com podem carregar l'alfabet en minúscula a Python mitjançant el mòdul de cadena:

Codi

 # Python program to print a list of alphabets # Importing the string module import string # Printing a list of lowercase alphabets lower = list(string.ascii_lowercase) print(lower) # Printing a list of uppercase alphabets upper = list(string.ascii_uppercase) print(upper) # Printing a list of both upper and lowercase alphabets alphabets = list(string.ascii_letters) print(alphabets) 

Sortida:

 ['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'] ['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'] ['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', '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'] 

Ús de les funcions chr i ord de Python

En aquesta part, descobrireu com crear una llista d'alfabets utilitzant les funcions integrades chr i ord. Un valor enter es transforma en el seu valor Unicode coincident mitjançant la funció chr de Python. La funció ord fa el mateix convertint un valor Unicode de nou al seu equivalent enter.

Construeix una llista de l'alfabet utilitzant un bucle For

Per crear una llista de les lletres en minúscules, podem fer un bucle sobre els valors enters del 97 al 122 mitjançant el mètode chr(). Els nombres enters que van del 97 al 122 s'utilitzen per representar les lletres minúscules de la a a la z. Afegirem cada lletra a una llista buida que crearem. Mireu com apareix això:

Codi

funció de subcadena de Java
 # Python program to generate a list of alphabets using the chr and ord functions list_ = [] for i in range(97, 123): list_.append(chr(i)) print(list_) 

Sortida:

 ['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'] 

Pot ser difícil recordar el que representa 97 (o 122). Això ens permet recórrer les altres 26 lletres després d'utilitzar el mètode ord() per obtenir el valor integral de l'alfabet 'g'. Fem una ullada a això.

Codi

 # Python program to show how to use the ord function to retrieve the integral value of any alphabet list_ = [] # Getting the integral value of the letter 'j' start_from = ord('g') for i in range(20): list_.append(chr(start_from + i)) print(list_) 

Sortida:

 ['g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 

Utilitzeu Python List Comprehension per fer una llista de l'alfabet

Ja sabem que una expressió s'avalua per a cada element d'un objecte iterable determinat. Per aconseguir-ho, podem construir una llista Python de l'alfabet iterant sobre l'objecte d'interval Python entre els números 97 i 122. Ho farem utilitzant la comprensió de llistes aquesta vegada.

programa java

Codi

 # Python program to generate a list of alphabets using the Python list comprehension and the chr() function # Initializing the list comprehension listt = [chr(v) for v in range(97, 123)] # Printing the list print(listt) 

Sortida:

 ['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'] 

Tot i que el nostre bucle for no era especialment complex, fer-lo una comprensió de llista de Python ho va fer molt més senzill! També podem convertir la nostra versió dinàmica addicional en una comprensió de llista de Python, tal com es mostra a continuació.

Codi

 # Python program to generate a list of alphabets using the Python list comprehension and the ord() function # Initializing the list comprehension listt = [chr(v) for v in range(ord('a'), ord('a') + 26)] # Printing the list print(listt) 

Sortida:

 ['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'] 

A la següent secció, descobrireu com crear una llista Python de l'alfabet mitjançant el mètode map().

Ús de la funció de mapa per construir una llista de l'alfabet

Utilitzarem el mètode map() en aquesta part per generar la llista de l'alfabet. Cada element de l'iterable es passa a la funció donada a la funció de mapa. Com a resultat, es pot assignar la funció chr de Python a cada element de l'objecte d'interval que inclou les lletres alfabètiques. Aquest mètode millora la llegibilitat aclarint quina operació es realitza en cada element de l'iterable.

comparació de cadena java

Examinem l'aparença d'aquest codi:

Codi

 # Python program to generate a list of alphabets using the Python map and the ord() function # Initializing the map function listt = list(map(chr, range(97, 123))) # Printing the list print(listt) 

Sortida:

 ['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'] 

Aquí, donem la funció chr, que l'intèrpret assignarà a cada element de l'objecte range() que abasta des del 97 al 123, al mètode map(). Atès que el mètode map() proporciona un objecte mapa, heu d'utilitzar el mètode list() per canviar-lo en una llista.

Python String isalpha()

Quan tots els caràcters de la cadena donada són alfabets, la funció isalpha() retornarà True. Si no, es retorna False.

La sintaxi de la funció Python isalpha() és:

 string.isalpha() 

Paràmetres d'isalpha():

La funció isalpha() no pren cap paràmetre.

Valor de retorn d'isalpha()

isalpha() produeix el resultat:

  • És cert si la cadena donada només conté caràcters alfabètics (la cadena pot contenir majúscules i minúscules).
  • Fals si un caràcter de la cadena no és un alfabet.

Exemple 1

Veurem el funcionament d'isalpha()

Codi

 # Python program to show how the isalpha() function works # Giving a normal string with all the characters as alphabets website = 'Javatpoint' print(f'All the characters of {website} are alphabets: ', website.isalpha()) # Giving the string that contains whitespace name = 'Peter Parker' print(f'All the characters of {name} are alphabets: ', name.isalpha()) # Giving a string that contains the number name = 'Peter2' print(f'All the characters of {name} are alphabets: ', name.isalpha()) 

Sortida:

 All the characters of Javatpoint are alphabets: True All the characters of Peter Parker are alphabets: False All the characters of Peter2 are alphabets: False 

Exemple 2

Utilitzant la funció isalpha() amb clàusules if-else.

topologies de xarxa

Codi

 # Python program to show how the isalpha() function works with if-else conditions # Initializing the strings string1 = 'PeterParker' string2 = 'Peter Parker' # Using the if else condition statements # Giving the first string if string1.isalpha() == True: print('All the characters of the given string are alphabet') else: print('All the characters of the given string are not alphabet') # Giving the second string if string2.isalpha() == True: print('All the characters of the given string are alphabet') else: print('All the characters of the given string are not alphabet') 

Sortida:

 All the characters of the given string are alphabet All the characters of the given string are not alphabet