[英]How can I replace the last character of a string for the first letter of the alphabet?
我目前正在编写一个代码,将单词中的每个字母,一个字母向上移动,例如:Abc 变为 Bcd,(第一个字母始终为大写),但是每当我在单词中键入 z 时,它就会变为 { 或 [ (如果是大写字母)。 例如,如果我输入 zoo,输出是“[pp”我希望 z 成为 a。 到目前为止,我已经尝试过这个:
word = input("Insert Word:")
word = word.capitalize().replace(" ", "")
for shift in word:
incrypt = chr(ord(shift)+1)
print (incrypt, end='')
我也试过使用这样的 if 语句:
word = input("Insert Word:")
word = word.capitalize().replace(" ", "")
for shift in word:
incrypt = chr(ord(shift)+1)
Last_char= incrypt[-1]
if Last_char > chr(123):
Last_char = [chr(97)]
print (incrypt, end='')
elif Last_char == chr(91):
Last_char = [chr(65)]
print (incrypt, end='')
但它没有用。
这是使用 join 的解决方案:
word = word.lower()
"".join(chr(ord('a') + (ord(w)-ord('a')+1)%26) for w in word).capitalize()
我会这样做:
word = input("Insert Word:")
word = word.capitalize().replace(" ", "")
A,Z = ord('A'), ord('Z')
a,z = ord('a'), ord('z')
step = 1
for shift in word:
new_char = ord(shift) + step
incrypt = None
if 'a' <= shift <= 'z':
incrypt = chr(new_char) if new_char <= z else chr(a + (new_char - z - 1)%26 )
elif 'A' <= shift <= 'Z':
incrypt = chr(new_char) if new_char <= Z else chr(A + (new_char - Z - 1)%26 )
else :
incrypt = shift
print (incrypt, end='')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.