【发布时间】:2016-01-01 08:40:56
【问题描述】:
我一直在使用 Python 并试图将字符串中的所有字母移动字母表中的 n 个空格,但是我遇到了很多错误。
print("Cryptography")
userInput = str(input("Write anything that you'd like to encrypt here: "))
userNumberInput = int(input("Please choose a number without decimals here: "))
userInput = userInput.lower()
wordCount = userInput.split()
loopRunner = int(0)
letterCount = list()
for word in range(len(wordCount)):
letterCount.insert(loopRunner,len(wordCount[loopRunner]))
print(letterCount[loopRunner])
loopRunner = loopRunner + 1
outputString = "" .join((chr(97 + (ord(letter) -97 + userNumberInput) % 26) for letter in userInput))
loopRunner = 0
for word in range(len(wordCount)):
outputString2 = [outputString[i:i+letterCount[loopRunner]] for i in range (0, len(outputString), letterCount[loopRunner])]
loopRunner = loopRunner + 1
finalResult = " " .join(outputString2)
print(finalResult)
到目前为止,它完成了我需要它做的事情,但是当我尝试运行它时,它似乎也将空格计为字母,我不知道如何排除它们,同时将它们保留在最终结果中,就像它们一样是。
我想知道的另一件事是我是否有任何方法可以防止字母变成小写字母并保持代码正常运行?
我已经尝试了好几个小时,但一直没有找到好的解决方案。
【问题讨论】:
-
您是要同时更改空格还是只更改字母并将空格保留为空格?
-
我想更改字母并将它们所在的空格保留为空格。我将如何存储空间的位置?我了解整个过程,但我什至不知道从哪里开始编写代码。你能给我一个简单的例子吗?
-
我正在研究一个解决方案,但它可能看起来像这样:在开始时:将所有空格的索引位置保存在列表中 userInput = userInput.replace(' ', '' ) 并在最后再次在这些索引位置添加空格。
标签: python string for-loop whitespace