显示变量值

2024-09-29 23:17:45 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

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)

如果我输入bad

输出:

b
a
d

问uestion:How can 我把字母表的值放在它旁边(在输出中),如下所示:

b 2
a 1
d 4

Tags: ofthe代码inforinputvaluelist
3条回答

一种通用的方法是借助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))

这样就不需要字典了

一个使用python3.6f-strings的线性程序

print("\n".join((f"{score} {scores[score]}" for score in scores))

或者如果你不能使用f-strings,你可以使用:

print(("\n".join("{} {}".format(score, scores[score]) for score in scores))

由于score是一个dict,您可以简单地使用x作为索引来获取其值:

for x in word:
  print(x, score[x])

相关问题 更多 >

    热门问题