python - 将整个单词下移索引

标签 python python-3.x

所以我试图将一个字母在索引范围内向下移动,例如当你将其移动“3”时,“a”变成“d”,但现在我想做一个完整的单词,这样每个字母都会同时向下移动时间,这是我到目前为止所拥有的:

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']
W=input("Enter Word: ")
S=int(input("Please choose a number between -51 and 51: "))
I=(Alphabet.index(W))
J=I+S
if J>25:
print("Please choose a number that is between -51 and 51")
else:
print("Your code word is: ",Alphabet[J])

输出是:

Enter Word: today
Please choose a number between -51 and 51: 3
Traceback (most recent call last):
File"C:/Users/Owner/OneDrive/Documents/Python/Word Shift.py", line 4, in <module>
I=(Alphabet.index(W))
ValueError: 'today; is not in list

仅供引用,我实际上是Python的初学者,所以我不知道很多“东西”,如果不是太麻烦,你能告诉我我哪里出错了以及你的编码解决方案的每个部分是什么是吗?

最佳答案

如果 element 不在 some_list 中,

some_list.index(element) 会引发 ValueError。除非输入的单词是一个字符,否则 Alphabet.index(W) 将会抛出此错误,因为 Alphabet 只是单个字符的列表。

您需要创建一个空列表,循环遍历 W 中的字符,使用 Alphabet.index 转换每个字符并将其追加到列表中。循环结束后,您可以使用 ''.join(some_list) 习惯用法将整个列表连接成一个字符串。

new_word_list = []
for char in W:
    I = Alphabet.index(char)
    new_word_list.append(Alphabet[I+S])
new_word = ''.join(new_word_list)

您的代码也将不起作用,因为您的 Alphabet 列表只有 26 个元素长,但用户可以输入一个使索引高于 26 的数字。例如,如果有人选择数字 1 和 'z' 是字符之一,您的代码将抛出索引错误,因为 Alphabet.index('z') 是 26,并且不存在第 27 个索引这样的东西。

最简单的解决方案(尽管效率不高)是在定义 Alphabet 时执行此操作:

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']*3

这意味着您的字母表列表将有 78 个元素长。

一旦您对 Python 更加熟悉,您可能需要查看内置函数,例如 chrord 以及 的内容strings 模块,它将简化您尝试做的一些事情。

关于python - 将整个单词下移索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27838813/

相关文章:

python - 将文档字符串添加到 __slots__ 描述符?

python-3.x - Scrapy - 抓取评论跳过 <br> 之后的文本

python - SQLalchemy 查询未提交

python - PYQT5:窗口没有获得焦点

Python - 索引错误 : list index out of range NOT being thrown when it should be

python - 带数学运算符的递归函数

python - 从文件中删除未混合的数字

python - 3g 覆盖 map - 可视化纬度、经度、ping 数据

python - python字典可以容纳多少个元素?

python - 累积自定义函数