Python ROT-13,字母为字符串

Python ROT-13,字母为字符串,python,rot13,Python,Rot13,我刚开始学习编程,会有一个愚蠢的问题。 我用字典制作了ROT-13,但后来我决定用字符串代替字典。但问题是: ROT_13 = "abcdefghijklmnopqrstuvwxyz" text_input = input("Enter your text: ") text_output = "" for i in text_input: text_output = text_output + ROT_13[i+13] print (text_output) 接下来发生了什么:

我刚开始学习编程,会有一个愚蠢的问题。 我用字典制作了ROT-13,但后来我决定用字符串代替字典。但问题是:

ROT_13 = "abcdefghijklmnopqrstuvwxyz"
text_input = input("Enter your text: ")
text_output = ""
for i in text_input:
        text_output = text_output + ROT_13[i+13]
print (text_output)
接下来发生了什么:

Traceback (most recent call last):
  File "D:/programming/challenges/challenge_61.py", line 5, in <module>
    text_output = text_output + ROT_13[i+13]
TypeError: must be str, not int
回溯(最近一次呼叫最后一次):
文件“D:/programming/challenges/challenge_61.py”,第5行,在
文本输出=文本输出+旋转13[i+13]
TypeError:必须是str,而不是int

那么,有溶液吗?或者最好使用字典而不是字符串?

您缺少转换:

ROT_13 = "abcdefghijklmnopqrstuvwxyz"
ROT_13_idx = {l: i for i, l in enumerate(ROT_13)}
text_input = input("Enter your text: ")
text_output = ''.join((ROT_13[(ROT_13_idx[i] + 13) % len(ROT_13)]
                       for i in text_input))

print(text_output)

i
的名称有误——它是字符串的一个字符,不是整数,作为数组索引将失败

简单地将13添加到索引将无法旋转字母表末尾附近的字母(模数运算符
%
对此很有用)

下面是对当前代码的有效修改,以帮助您开始。它的工作原理是使用
find()
定位正确的字符,然后将13添加到找到的索引中,最后使用
%
处理换行。请注意,
find()
是线性时间

ROT_13 = "abcdefghijklmnopqrstuvwxyz"
text_input = input("Enter your text: ")
text_output = ""
for i in text_input:
    text_output += ROT_13[(ROT_13.find(i)+13)%len(ROT_13)]
print(text_output)
下面是另一种使用字典和
zip
的方法:

from string import ascii_lowercase as alpha

rot13 = dict(zip(alpha, alpha[13:] + alpha[:13]))
print("".join(map(lambda x: rot13[x] if x in rot13 else x, input("Enter your text: "))))

当字符不按字母顺序排列但不按大写字母排列时,这也会处理一个重要的大小写(读者练习)。

i是字符串数据类型,错误清楚地显示您正在向字符串添加
13
。使用
ord()
chr()
再次将字符串更改为数字。如果您看到我的代码与字典一起工作,您将看到palm:D所以,如果我将+13添加到索引,我将超出索引范围,对吗?是的,但您可以使用try。。。除了在结果索引器上,并将未旋转的字符附加到输出字符串。ROT13在非字母输入时不应崩溃。