我要创建一个程序,得到一个字符串,整数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进一步增加检测的数学增量”,所以‘回来’到‘一’。
任何建议?提前致谢。
这是一种作弊的,但这里是我采取的方法:
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
循环,而不是上面。
让我们来分析一下,以便与命名的变量各个步骤让你处理清楚什么用:
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 ) )
下面是从意见修改后的答案:
c = chr((ord(a) - 97) % 25 + 97)