Wie erstelle ich eine Liste von Buchstaben des Alphabets, ohne es manuell wie folgt zu tun?
['a', 'b', 'c', 'd', ..., 'z']
Wie erstelle ich eine Liste von Buchstaben des Alphabets, ohne es manuell wie folgt zu tun?
['a', 'b', 'c', 'd', ..., 'z']
>>> import string
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> list(string.ascii_lowercase)
['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']
Alternativ, unter Verwendung von range
:
>>> list(map(chr, range(97, 123)))
['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']
Oder äquivalent:
>>> list(map(chr, range(ord('a'), ord('z')+1)))
['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']
Weitere hilfreiche Funktionen des Moduls string
:
>>> help(string)
....
DATA
ascii_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digits = '0123456789'
hexdigits = '0123456789abcdefABCDEF'
octdigits = '01234567'
printable = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
punctuation = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
whitespace = ' \t\n\r\x0b\x0c'
In Python 2.7 und 3 können Sie dies verwenden:
import string
string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Wie @Zaz sagt: string.lowercase
ist veraltet und funktioniert nicht mehr in Python 3, aber string.ascii_lowercase
funktioniert in beiden
Hier ist eine einfache Buchstabenbereich-Implementierung:
Code
def letter_range(start, stop="{", step=1):
"""Geben Sie einen Bereich von Kleinbuchstaben zurück."""
for ord_ in range(ord(start.lower()), ord(stop.lower()), step):
yield chr(ord_)
Demo
list(letter_range("a", "f"))
# ['a', 'b', 'c', 'd', 'e']
list(letter_range("a", "f", step=2))
# ['a', 'c', 'e']
CodeJaeger ist eine Gemeinschaft für Programmierer, die täglich Hilfe erhalten..
Wir haben viele Inhalte, und Sie können auch Ihre eigenen Fragen stellen oder die Fragen anderer Leute lösen.