0

I need to create a function that replaces a letter with the letter 13 letters after it in the alphabet (without using encode). I'm relatively new to Python so it has taken me a while to figure out a way to do this without using Encode.

Here's what I have so far. When I use this to type in a normal word like "hello" it works but if I pass through a sentence with special characters I can't figure out how to JUST include letters of the alphabet and skip numbers, spaces or special characters completely.

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

EDIT

I tried using .isalpha() but this doesn't seem to be working for me - characters are duplicating for some reason when I use it. Is the following format correct:

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
4

1 回答 1

0

从评论开始。建议 OP 使用 isalpha,并想知道为什么会导致重复(请参阅 OP 的编辑)

这与使用isalpha无关,它与第二个 for 循环有关

for i in c:

没有必要,并且导致重复。你应该删除它。相反,您可以只使用index = a.index(i). 您已经这样做了,但由于某种原因附加到列表并导致混乱

index任何时候都可以ifor i in c循环中使用该变量。附带说明一下,在嵌套的 for 循环中尽量不要重用相同的变量。它只会引起混乱......但这是代码审查的问题

假设您做对了所有事情,它应该可以工作。

于 2017-09-07T08:56:10.613 回答