如何增加字母字符而不在z之后获得特殊字符?

2024-06-02 08:36:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须创建一个程序来获取一个字符串和一个整数;它将字符串的每个字符增加n个字符;例如,如果字符串是“abc”和n=1,则输出将是“bcd”,如果n=2,则输出将是“cde”。你知道吗

到目前为止,我已经写了这个代码

string = list( input( "Insert a string, it will be codified: " ) )

n = int( input( "Insert an integer, each string's character will be increased by that number: " ) )

for characterIndex in range( len( string ) ):

    string[characterIndex] = chr( ord( string[characterIndex] ) + n )

print( ''.join( string ) )

尽管如此,如果我输入“xyz”并且n=1,我会得到“yz{”,这是有意义的,因为ascii的下一个字符“z”是“{”。你可以想象,对于一个更高的n,情况会变得更糟;我一直试图用模来解决任何n的问题,试图利用26个字母的事实,但我仍然找不到一个数学增量来检测字符串的增量何时超过了“z”,所以它“返回”到“a”。你知道吗

有什么建议吗?提前谢谢。你知道吗


Tags: 字符串程序inputstring整数be字符will
3条回答

这有点作弊,但我会采取以下方法:

def string_bump(s):
    letter_list = "abcdefghijklmnopqrstuvwxyza" #note the extra 'a' at the end
    old_positions = []; new_positions = []
    for character in s:
        old_positions.append(letter_list.find(character))
    for pos in old_positions:
        new_positions.append(pos+1)
    new_string = ""
    for pos in new_positions:
        new_string += letter_list[pos]
    return new_string

for s in ["abc", "bcd", "xyz"]:
    print("before:", s, "after:", string_bump(s))

印刷品:

before: abc after: bcd
before: bcd after: cde
before: xyz after: yza

基本上,我扫描字符串以将字符转换为字母表字符串中的位置;为每个位置添加1;然后从这些位置重建字符串。“作弊”是加上一个额外的'a',这样一个位置-25(从0开始计数)'z'转换成额外的位置-26'a'。你知道吗

如果这冒犯了你,你可以省去多余的'a',而只是在位置列表中进行另一次传递,当你看到'26'(这将超过没有'a'的letter_list的结尾)时,把它降到零。你知道吗

对于您的示例,这只是一个概念证明;为了支持任意移位,您需要将letter_list扩展为完整的字母表,并在输入上使用模(例如n = n%26),以确保输入保持在范围内。你知道吗

另外,我实际上会使用列表表达式来代替for循环,但是您可能还没有遇到这些循环,所以我在上面使用了更显式的for循环。你知道吗

以下是评论中修改后的答案:

c = chr((ord(a) - 97) % 25 + 97)

让我们将其分解,以便使用命名变量的各个步骤清楚地说明您要处理的内容:

asciiValue = ord(string[characterIndex])
alphabetIndex = asciiValue - ord('a')
alphabetIndex = (alphabetIndex + n) % 26
asciiValue = alphabetIndex + ord('a')
string[characterIndex] = chr(asciiValue)

请注意,上面假设您的输入字符串仅由小写ASCII字母组成。对于大写字符,您需要减法(并重新添加)ord('A')。你知道吗

将其集成到现有代码中:

def shift_letter(letter, n):
    asciiValue = ord(letter)
    alphabetIndex = asciiValue - ord('a')
    alphabetIndex = (alphabetIndex + n) % 26
    asciiValue = alphabetIndex + ord('a')
    return chr(asciiValue)

string = list( input( "Insert a string, it will be codified: " ) )

n = int( input( "Insert an integer, each string's character will be increased by that number: " ) )

for characterIndex in range( len( string ) ):
    string[characterIndex] = shift_letter(string[characterIndex], n)

print( ''.join( string ) )

相关问题 更多 >