我需要创建一个函数,用字母后面的13个字母替换一个字母(不使用编码)。我对Python相对来说比较陌生,所以我花了一段时间才找出一种不使用Encode的方法。ROT 13密码:创建函数Python
这是我到目前为止。当我用它来输入一个像“hello”这样的正常单词时,它可以工作,但是如果我通过一个带有特殊字符的句子,我不知道如何包含字母表中的字母以及跳过数字,空格或特殊字符完全。
def rot13(b):
b = b.lower()
a = [chr(i) for i in range(ord('a'),ord('z')+1)]
c = []
d = []
x = a[0:13]
for i in b:
c.append(a.index(i))
for i in c:
if i <= 13:
d.append(a[i::13][1])
elif i > 13:
y = len(a[i:])
z = len(x)- y
d.append(a[z::13][0])
e = ''.join(d)
return e
编辑
我尝试使用.isalpha(),但这似乎并没有为我工作 - 字符复制出于某种原因,当我使用它。以下格式是否正确:
def rot13(b):
b1 = b.lower()
a = [chr(i) for i in range(ord('a'),ord('z')+1)]
c = []
d = []
x = a[0:13]
for i in b1:
if i.isalpha():
c.append(a.index(i))
for i in c:
if i <= 12:
d.append(a[i::13][1])
elif i > 12:
y = len(a[i:])
z = len(x)- y
d.append(a[z::13][0])
else:
d.append(i)
if message[0].istitle() == True:
d[0] = d[0].upper()
e = ''.join(d)
return e
也许如果检查'character.isalpha()'会有帮助吗? “character”被替换为你用来容纳角色的任何可变因子 –
这听起来像是一个用正则表达式很容易解决的问题。 –
嗨@LukeK我尝试使用character.isalpha()如你所建议的。你能看看我的编辑,让我知道我做错了什么?出于某种原因,当我使用.isalpha() –