gpt4 book ai didi

python - 变量的显示值

转载 作者:太空宇宙 更新时间:2023-11-04 07:52:42 25 4
gpt4 key购买 nike

代码:

score={'a':1,'b':2,'c':3,'d':4,'e':5} #value of the alphabet

a=1
b=2
c=3
d=4
e=5

word=input('Enter a word:')
word_list=list(word)
for x in word:
print(x)

如果我输入错误

输出:

b
a
d

问题:如何将字母表的值放在它旁边(在输出中),如下所示:

b 2
a 1
d 4

最佳答案

一种通用的方法是借助 ord 函数,它表示字母的整数值

for letter in ['b', 'a', 'd']:
print(letter + ' ' + str(ord(letter) - ord('a') + 1))

word = 'test'
for letter in word:
print(letter + ' ' + str(ord(letter) - ord('a') + 1))

这样就不需要字典了

关于python - 变量的显示值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52737248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com