Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将字符串的最后一个字符替换为字母表的第一个字母?_Python - Fatal编程技术网

Python 如何将字符串的最后一个字符替换为字母表的第一个字母?

Python 如何将字符串的最后一个字符替换为字母表的第一个字母?,python,Python,我目前正在编写一个代码,将一个单词的每个字母向上移动一个字母,例如:Abc变为Bcd(第一个字母总是大写),但每当我在一个单词中键入z时,它就会变为{或[(如果是大写字母)。例如,如果我键入zoo,输出是“[pp”,我希望z变为a。到目前为止,我已经尝试了以下方法: word = input("Insert Word:") word = word.capitalize().replace(" ", "") for shift in

我目前正在编写一个代码,将一个单词的每个字母向上移动一个字母,例如: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='')
word=input(“插入单词:”)
word=word.capitalize().replace(“,”)
A、 Z=ord('A'),ord('Z'))
a、 z=ord('a'),ord('z'))
步骤=1
对于单词的移位:
新字符=ord(移位)+步骤
incrypt=无

如果在第二个代码示例中的“a”是
incrypt=chr(ord(shift)+1).
与前面的
for
循环无关?或者我猜,是
for
循环要缩进吗?
incrypt=chr(ord(shift)+1)如果shift!=“z”否则“a”
?请提供预期结果。显示中间结果与预期结果的不同之处。我们应该能够复制和粘贴连续的代码块,执行该文件,并再现您的问题以及跟踪问题点的输出。这使我们能够根据您的测试数据和所需输出测试我们的建议。“它不起作用”不是一个问题规范。您发布的代码无法运行。您的代码应该包含对字母
z
z
的显式检查;可能是出于某种原因,您将它们编码为整数。