【问题标题】:Python Caesar cipher changes capitalization of the given input stringsPython Caesar cipher 更改给定输入字符串的大小写
【发布时间】:2023-03-09 09:45:02
【问题描述】:

在凯撒密码中,我需要我的大写字符保持大写,非字母字符保持非字母/相同。我可以使用小写字母。

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

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

【问题讨论】:

    标签: python encryption caesar-cipher


    【解决方案1】:

    您可以使用i.isalpha() 来检查当前字符是否为字母,您可以使用i.isupper() 来检查当前字母是否为大写。转换字母时,您需要将字母变为小写,然后将其转换回大写。除了这些更改之外,您的输入还有太多括号。我使用的是 raw_input,因为我使用的是 python 2.7。由于缩进错误,您的格式是如此偏离您发布的代码将无法运行,并且您的行 if i == "" 检查空字符串而不是我假设您要查找的空格。这里所说的就是我对您的代码所做的,以尝试使其与您的代码相似,同时删除无关的部分。

    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
    

    【讨论】:

    • @jaco 如果这对您有所帮助,请不要忘记投票并给它绿色检查,以便将来对人们有所帮助
    猜你喜欢
    • 2016-01-06
    • 2021-08-16
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-09
    相关资源
    最近更新 更多