在python中如何使字符串的每个字母都成为变量

2024-09-21 09:46:08 发布

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

我正在尝试用python编写一个编码器

代码在这里。它工作得很好,但我想把字符串中的每个字母改成相应的数字,例如:a=1,b=2。所以最后会变成一个数词。我的目标是有两个程序,一个用于编码,一个用于解码

print "Welcome to the encoder"
Letter1 = raw_input ("Please input the first letter of the word: ")
Letter2 = raw_input ("Please input the second letter of the word: ")
Letter3 = raw_input ("Please input the third letter of the word: ")
Letter4 = raw_input ("Please input the fourth letter of the word: ")
Letter5 = raw_input ("Please input the fifth letter of the word: ")
Letter6 = raw_input ("Please input the sixth letter of the word: ")
Letter7 = raw_input ("Please input the seventh letter of the word: ")
Letter8 = raw_input ("Please input the eighth letter of the word: ")
Letter9 = raw_input ("Please input the ninth letter of the word: ")
Letter10 = raw_input ("Please input the tenth letter of the word: ")
Letter11 = raw_input ("Please input the eleventh letter of the word: ")
Letter12 = raw_input ("Please input the twelvth letter of the word: ")
print "Your code is " + Letter3 + Letter2 + Letter1 + Letter6 + Letter5 
+ Letter4 + Letter9 + Letter8 + Letter7 + Letter12 + Letter11 + 
Letter10

Tags: oftheinputrawwordprintpleaseletter
3条回答

如果使用一个列表并将每个raw_input附加到列表中,那么它将比使用变量存储每个字母更简洁、更易于缩放。在

print "Welcome to the encoder"
code_length = 12
code = []
for index in xrange(0, code_length):
    letter = raw_input  ("Please input letter " + str(index) + " of the word: ")
    ordinal = ord(letter) - 96
    code.append(str(ordinal))

print ' '.join(code)

您可以在python中使用ord()方法并执行此操作。在

word = raw_input()

print('Your code is\n')
for letter in word:
    print ord(letter)-96

您可以使用dict(字典)来存储每个字母及其对应的数字。如果您想将代码更改为字母序号以外的代码,这是灵活的。在

# define the dictionary
encoder = {"a":"1", "b":"2", "c":"3", "d":"4", "e":"5"}

# take your input
Letter1 = raw_input ("Please input the first letter of the word: ")
Letter2 = raw_input ("Please input the first letter of the word: ")
Letter3 = raw_input ("Please input the first letter of the word: ")

# print out the encoded version
print encoder[Letter1] + encoder[Letter2] + encoder[Letter3]

相关问题 更多 >

    热门问题