[英]rot13 not translating correctly python
I'm trying to translate a string into rot13 so I've written the following code: 我正在尝试将字符串转换为rot13,所以我编写了以下代码:
def str_rot_13(my_string):
list_string = list(my_string)
number_string = [ord(x) for x in list_string]
new_number_string = [x + 13 for x in number_string]
new_list_string = [chr(x) for x in new_number_string]
my_new_string = ''.join(new_list_string)
return my_new_string
My issue is that if I get to far down in the alphabet it starts to return weird numbers and slashes. 我的问题是,如果我在字母表中向下走,它会开始返回奇怪的数字和斜线。 I tried creating a range in ord('a') to ord('z') but it still returned the numbers and slashes.
我尝试在ord('a')中创建一个范围到ord('z'),但它仍然返回数字和斜杠。 Any help would be appreciated!
任何帮助,将不胜感激!
by doing (((x + 13-97)%26)+97)
X value will always be between 97 and 122 ( ord("a") = 97, ord("z") = 122
) then you're output will always be a string exclusively composed of letters. 通过做
(((x + 13-97)%26)+97)
X值将始终在97和122之间( ord("a") = 97, ord("z") = 122
)然后你输出将始终是一个完全由字母组成的字符串。
def str_rot_13(my_string):
list_string = list(my_string)
number_string = [ord(x) for x in list_string]
new_number_string = [(((x + 13-97)%26)+97) for x in number_string]
new_list_string = [chr(x) for x in new_number_string]
my_new_string = ''.join(new_list_string)
return my_new_string
output:
输出:
>>> print str_rot_13("my string")
zlafgevat
>>>
The idea of rot13 is that there are 26 letters in the (English) alphabet. rot13的想法是(英文)字母表中有26个字母。 Thus applying rot13 gives you the original string.
因此,应用rot13会为您提供原始字符串。
ord
, however gives you the Ascii symbol (there are 128 of those). 然而,
ord
会给你Ascii符号(其中有128个)。
How about using string.ascii_lowercase
如何使用
string.ascii_lowercase
import string
def str_rot_13(my_string):
alphabet = list(string.ascii_lowercase)
list_string = list(my_string)
number_string = [alphabet.index(x) for x in list_string]
new_number_string = [x + 13 for x in number_string]
new_list_string = [alphabet[x%26] for x in new_number_string]
my_new_string = ''.join(new_list_string)
return my_new_string
Or shorter 或者更短
def rot13(s):
alphabet = list(string.ascii_lowercase)
chars = map(lambda x: alphabet[(alphabet.index(x) + 13) %26], s)
return ''.join(chars)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.