def main():
# open file to be used
inFile = open ('input.txt', 'r')
fileContent = inFile.readline()
choice = input('Do you want to encrypt or decrypt? (E / D): ')
# find even and odd characters in string
if (choice == 'E'):
for i in range(0, len(fileContent), 2):
even_str = fileContent[i]
print(even_str)
for i in range(1, len(fileContent), 2):
odd_str = fileContent[i]
encrypted_str = odd_str + even_str
# open outfile and write new strings in
outFile = open("output.txt", "w")
outFile.write(even_str)
outFile.write(odd_str)
outFile.write(encrypted_str)
outFile.close()
if (choice == 'D'):
half = fileContent // 2
even_str = fileContent[:half]
# return this if user has incorrect input
if (choice != 'E' and choice != 'D'):
print ('')
print ('Wrong input. Bye.')
return
inFile.close()
main()现在我只是测试一下even_str的输出是什么。输入是“敏捷的棕色狐狸跳过懒狗”。我一直得到的even_str输出是"g“,而我应该得到的是每个偶数字符。
发布于 2014-04-05 11:52:20
每次通过循环都会为even_str分配一个新值,因此当循环完成时,该值将是上次分配的值--在本例中是'g‘。如果您想要一个包含所有偶数字符的列表,则需要将其作为列表,并将每个字符附加到该列表中:
even_str = list()
for i in range(0, len(fileContent), 2):
even_str.append(fileContent[i])https://stackoverflow.com/questions/22876316
复制相似问题