将字符串中的每个字符更改为字母表中的下一个字符

Vit*_*ito 2 python string python-2.7

我在 Ubuntu 上使用 PyCharm 在 Python 2.7 中编码。

我正在尝试创建一个函数,该函数将接受一个字符串并将每个字符更改为字母表中的下一个字符。

def LetterChanges(str):
    # code goes here
    import string
    ab_st = list(string.lowercase)
    str = list(str)
    new_word = []
    for letter in range(len(str)):
        if letter == "z":
            new_word.append("a")
        else:
            new_word.append(ab_st[str.index(letter) + 1])
        new_word = "".join(new_word)
    return new_word


# keep this function call here
print LetterChanges(raw_input())
Run Code Online (Sandbox Code Playgroud)

当我运行代码时,出现以下错误:

/usr/bin/python2.7 /home/vito/PycharmProjects/untitled1/test.py
test
Traceback (most recent call last):
  File "/home/vito/PycharmProjects/untitled1/test.py", line 17, in <module>
    print LetterChanges(raw_input())
  File "/home/vito/PycharmProjects/untitled1/test.py", line 11, in LetterChanges
    new_word.append(ab_st[str.index(letter) + 1])
ValueError: 0 is not in list

Process finished with exit code 1
Run Code Online (Sandbox Code Playgroud)

我在第 11 行在做什么?如何在字母表中为每个字符获取以下字符并将其附加到新列表中?

非常感谢。

daw*_*awg 6

我认为你让这太复杂了。

只需使用模数滚动到字符串的开头:

from string import ascii_letters

s='abcxyz ABCXYZ'
ns=''
for c in s:
    if c in ascii_letters:
        ns=ns+ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)]
    else:
        ns+=c
Run Code Online (Sandbox Code Playgroud)

如果您愿意,您可以将其减少为单个不可读的行:

''.join([ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)] 
             if c in ascii_letters else c for c in s])
Run Code Online (Sandbox Code Playgroud)

无论哪种情况,

Turns      abcxyz ABCXYZ
into       bcdyzA BCDYZa
Run Code Online (Sandbox Code Playgroud)

如果您希望它仅限于小写字母的大写,只需更改导入:

from string import ascii_lowercase as letters

s='abcxyz'
ns=''
for c in s:
    if c in letters:
        ns=ns+letters[(letters.index(c)+1)%len(letters)]
    else:
        ns+=c
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这种方法而不是我自己的答案。我专门尝试处理 OP 代码中的错误。点赞 :) (2认同)