我在 Python 2.7 中使用 PyCharm 在 Ubuntu 上进行编码。
我正在尝试创建一个函数,它将接受一个字符串并将每个字符更改为字母表中的下一个字符。
def LetterChanges(str):
# code goes here
import string
ab_st = list(string.lowercase)
str = list(str)
new_word = []
for letter in range(len(str)):
if letter == "z":
new_word.append("a")
else:
new_word.append(ab_st[str.index(letter) + 1])
new_word = "".join(new_word)
return new_word
# keep this function call here
print LetterChanges(raw_input())
当我运行代码时,出现以下错误:
/usr/bin/python2.7 /home/vito/PycharmProjects/untitled1/test.py
test
Traceback (most recent call last):
File "/home/vito/PycharmProjects/untitled1/test.py", line 17, in <module>
print LetterChanges(raw_input())
File "/home/vito/PycharmProjects/untitled1/test.py", line 11, in LetterChanges
new_word.append(ab_st[str.index(letter) + 1])
ValueError: 0 is not in list
Process finished with exit code 1
我在第 11 行做什么?如何为每个字符获取字母表中的以下字符并将其附加到新列表?
非常感谢。
原文由 Vito 发布,翻译遵循 CC BY-SA 4.0 许可协议
我认为你把它弄得太复杂了。
只需使用模数滚动到字符串的开头:
如果您愿意,可以将其减少到一个不可读的行:
无论哪种情况,
如果您希望它仅限于大写字母或小写字母,只需更改导入: