-1

我刚开始学习编程,会有愚蠢的问题。我使用字典制作了 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

那么,有什么解决办法吗?还是更好地使用字典而不是字符串?

4

2 回答 2

0

您缺少转换:

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)
于 2018-03-23T05:54:22.730 回答
0

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: "))))

当字符不是字母但不处理大写时,这也处理了一个重要的情况(读者练习)。

于 2018-03-23T06:05:58.540 回答