Search code examples
pythonencryptioncaesar-cipher

Python Caesar cipher changes capitalization of the given input strings


In a ceasar cipher I need it to be that my upper characters remain upper and that non letter character remain non letters/the same. I have it that I can work with lower letters.

Upper letters however are converted to lower and a different letter. Non-letter characters are converted to a lower letter as well. Upper letters must shift but remain upper. Non-letter characters must remain as non-letter character.

p = raw_input(("enter a word"))
n = input(("how many must it shift"))
a = 0
b = 0
c = 0
d = 0

for i in p:
    if i.isupper():
        a += 1
    elif i.islower():
        b += 1
    elif i.isdigit():
        c += 1
    else:
        d += 1
e = ""

for i in p:
    if i == "":
    e += i
else:
    integerValue = ord(i)
    integerValue-= 97
    integerValue += n
    integerValue %= 26
    integerValue += 97
    e += chr(integerValue)

    print e

Solution

  • You can use i.isalpha() to check if the current character is a letter or not and you can use i.isupper() to check if the current letter is uppercase or not. When you convert the letter you will need to make the letter lowercase and then convert it back to upper. On top of those changes you have too many parenthesis for your inputs. I used raw_input since I'm using python 2.7. Your formatting is so off your code that's posted won't run due to indentation errors and your line if i == "" checks for an empty string instead of a space which I am assuming you were going for. All that said here is what I did to your code to try and keep it similar to what you had while cutting out extraneous bits.

    p = raw_input("enter a word")
    n = int(raw_input("how many must it shift"))
    e = ''
    for i in p:
        if not i.isalpha():
            e+=i
        else:
            integerValue = ord(i.lower())
            integerValue-= 97
            integerValue += n
            integerValue %= 26
            integerValue += 97
            if i.isupper():
                e += chr(integerValue).upper()
            else:
                e += chr(integerValue)
    
    print e