Search code examples
pythonrot13

ROT-13 with alphabet in string


I'm just started to learn programming, and there'll be stupid question. I made ROT-13 using dictionary, but then I decided to use string instead of dictionary. But there's the problem:

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)

What's going on then:

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

So, is there any soulution? or better to use dictionary instead of string?


Solution

  • i is misleadingly named--it is a character of your string, not an integer, and will fail as an array index.

    Simply adding 13 to an index will fail to rotate letters close to the end of the alphabet (the modulus operator % is useful for this).

    Here's a working modification of your current code to get you started. It works by locating the correct character using find(), then adds 13 to the found index, and finally handles wrapping with %. Note that find() is linear time.

    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)
    

    Here's another way using a dictionary and 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: "))))
    

    This also handles an important case when the character isn't alphabetical but doesn't handle uppercase (exercise for the reader).