Python 凯撒密码更改给定输入字符串的大写

Python Caesar cipher changes capitalization of the given input strings

在 ceasar 密码中,我需要它是我的大写字符保持大写并且非字母字符保持非 letters/the 相同。我知道我可以使用小写字母。

然而,大写字母被转换为小写字母和不同的字母。非字母字符也会转换为小写字母。大写字母必须移动但保持大写。非字母字符必须保留为非字母字符。

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

您可以使用i.isalpha()检查当前字符是否为字母,您可以使用i.isupper()检查当前字母是否为大写。转换字母时,您需要将字母设为小写,然后再将其转换回大写。在这些更改之上,您的输入有太多括号。我使用 raw_input 因为我使用的是 python 2.7。由于缩进错误,您的格式与您发布的代码不符 运行 并且您的行 if i == "" 检查空字符串而不是我假设您想要的 space .这里所说的就是我对你的代码所做的,试图让它与你所拥有的相似,同时删除无关的位。

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