有人可以帮我弄清楚如何将加密句子的所有字母保留在同一行上。该代码可以工作,尽管很长哈。
sentence = raw_input('Enter a sentence to be encrypted ')
shift = input('Enter a shift value ')
def createDict (shift):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,'
alphaList=[]
for letter in alphabet:
alphaList.append(letter)
alphaDict={}
for letter in alphaList:
valueLetterIndex = (alphaList.index(letter) + shift)%len(alphaList)
valueLetter = alphaList[valueLetterIndex]
alphaDict[letter] = valueLetter
return alphaDict
def encryptText(sentence, shift):
dict = createDict(shift)
for letter in sentence:
encryptC = dict [letter]
print encryptC
print encryptText(sentence, shift)
最佳答案
收集列表中的加密字符,然后打印连接结果:
def encryptText(sentence, shift):
encryptionmap = createDict(shift)
output = []
for letter in sentence:
output.append(encryptionmap[letter])
print ''.join(output)
我将您的 dict
变量重命名为 map
以避免屏蔽内置 dict
类型。
您的createDict
函数可以简化为:
def createDict (shift):
alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .,'
alphaDict = {}
for pos, letter in enumerate(alphabet):
valueLetterIndex = (pos + shift) % len(alphabet)
valueLetter = alphabet[valueLetterIndex]
alphaDict[letter] = valueLetter
return alphaDict
因为字符串就像列表一样是一个序列;无需先转换为列表。通过使用enumerate
,我们省去了查找每个字母索引的麻烦。
关于Python凯撒Cypher助力一个级别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12695376/