ROT 13 Cipher: Creating a Function Python

718 views Asked by At

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
1

There are 1 answers

0
Luke K On BEST ANSWER

Following on from comments. OP was advised to use isalpha, and wondering why that's causing duplication (see OP's edit)

This isn't tied to the use of isalpha, it's to do with the second for loop

for i in c:

isn't necessary, and is causing the duplication. You should remove that. Instead you can do the same by just using index = a.index(i). You were already doing this, but for some reason appending to a list instead and causing confusion

Use the index variable any time you would have used i inside the for i in c loop. On a side note, in nested for loops try not to reuse the same variables. It just causes confusion...but that's a matter for code review

Assuming you do all that right it should work.