我试图将字符分配给值线的最小量可能
这就是我所知道的全部方法。我查看了其他解决方案,但似乎无法使它们工作
letter = random.randint(1,26)
if letter == 1:
actualLetter = "A"
elif letter == 2:
actualLetter = "B"
elif letter == 3:
actualLetter = "C"
elif letter == 4:
actualLetter = "D"
elif letter == 5:
actualLetter = "E"
elif letter == 6:
actualLetter = "F"
elif letter == 7:
actualLetter = "G"
elif letter == 8:
actualLetter = "H"
elif letter == 9:
actualLetter = "I"
elif letter == 10:
actualLetter = "J"
elif letter == 11:
actualLetter = "K"
elif letter == 12:
actualLetter = "L"
elif letter == 13:
actualLetter = "M"
elif letter == 14:
actualLetter = "N"
elif letter == 15:
actualLetter = "O"
elif letter == 16:
actualLetter = "P"
elif letter == 17:
actualLetter = "Q"
elif letter == 18:
actualLetter = "R"
elif letter == 19:
actualLetter = "S"
elif letter == 20:
actualLetter = "T"
elif letter == 21:
actualLetter = "U"
elif letter == 22:
actualLetter = "V"
elif letter == 23:
actualLetter = "W"
elif letter == 24:
actualLetter = "X"
elif letter == 25:
actualLetter = "Y"
elif letter == 26:
actualLetter = "Z"
actualLetter
被分配了与该值相对应的字母。
答案 0 :(得分:4)
您可以使用string.ascii_uppercase
:
import random
from string import ascii_uppercase:
letter = random.randint(1, 26)
actualLetter = ascii_uppercase[letter - 1]
更好的是,使用random.choice
(优选溶液):
actualLetter = random.choice(ascii_uppercase)
或者,而不string.ascii_uppercase
:
letter = random.randint(1, 26)
actualLetter = chr(letter + ord('A') - 1)
答案 1 :(得分:0)
您可以使用'ord()'和'chr()'依靠内置的ascii映射
在[8]中:ord('A')
出[8]:65
在[9]中:chr(65)
出[9]:“ A”