如何在z之后不增加特殊字符的情况下递增字母字符?

时间:2019-02-02 04:05:33

标签: python character ascii increment

我必须创建一个获取字符串和整数 n 的程序;它将字符串的每个字符增加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”。

有什么建议吗?预先感谢。

3 个答案:

答案 0 :(得分:1)

这是一种作弊的,但这里是我采取的方法:

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“Z”(从0计数)转化为额外的位置26“一个”。

如果那样冒犯了您,您可以省去多余的“ a”,而只需在位置列表中再过一遍,当您看到“ 26”(在letter_list的末尾没有的 'a'),敲它下降到零。

这仅仅是一个证明的概念为您的示例;以支持任意的变速,你会延长letter_list出为全字母,并在输入使用模数(例如,n = n%26),以确保输入在范围留了下来。

此外,我实际上将使用列表表达式代替for循环,但是您可能还没有遇到过这些表达式,因此我在上面使用了更明确的for循环。

答案 1 :(得分:0)

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

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 ) )

答案 2 :(得分:-1)

这是评论的修改后答案:

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