我目前正在编写Caesar Cipher。
问题是字母表列表不包含空格,所以当我尝试创建一个句子时(因为它用空格分隔)我得到一个错误,只有单个单词/字母起作用...
此处的代码:
#Creating Lists
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#Unpickling Dictionary
unpickle_codedwords = open("CWs.txt", "rb")
codedwords = pickle.load(unpickle_codedwords)
unpickle_codedwords.close()
###############################################################
""" #
IMPROVMENTS: #
Spaces/Sentences dont work <-- bob is a boy (ERROR) #
""" #
###############################################################
loop = 0#Using this to make my program loop continously
while loop == 0:
choice=int(input("What would you like to do?\n1)Code a word\n2)Decode a word\n3)Print the coded words list\n4)Quit the program\n5)Clear Coded Words List\n>>>"))#Asking for choice from user
if choice ==1:#If the choice selected was 1:
word=input("Enter the word you want to code\n>>>")
offset=int(input("Enter the offset below\n>>>"))
if word.isalpha() ==True:#checking alphabet only
for letter in word.lower(): # getting index of everysingle letter and converting it to lowercase
index=alphabet.index(letter)
index=index+offset#adding the index to the offset to create new index
while index>25:#if index is more than 25 i have to while loop it
index=index-26#creatingn the new index
codedwords.append([alphabet[index]])#appending each letter to word
#print(alphabet[index])<-- REMOVE LATER
answer = [''.join([x[0] for x in codedwords])] #instead of print(codedwords) because that prints[i],[i],[i] not iii
print(answer)
while word.isalpha()==False:#if word is not alphabeticals
print("Invalid Entry!, Please Try again\n")#loop it around again untill it's correct
word=input("Enter the word you want to code\n>>>")
if word.isalpha()==True:#looping round untill correct
for letter in word.lower():
index=alphabet.index(letter)
index=index+offset#Repeated again as above
while index>25:
index=index-26
codedwords.append([alphabet[index]])
answer = [''.join([x[0] for x in codedwords])]
print(answer)
答案 0 :(得分:0)
您可以使用all
检查用户输入(word
)中的所有字母是否为字母数字或空格:
while all(True if letter in alphabet + [' '] else False for letter in word):
>>> all([True, True])
True
>>> all([True, False])
False
>>>
之后:
for letter in word:
if letter == ' ':
codedwords.append([letter])
else:
# Code the letter