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

新手上路,请多包涵

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

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

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

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

 /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

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

非常感谢。

原文由 Vito 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 553
1 个回答

我认为你把它弄得太复杂了。

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

 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

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

 ''.join([ascii_letters[(ascii_letters.index(c)+1)%len(ascii_letters)]
             if c in ascii_letters else c for c in s])

无论哪种情况,

 Turns      abcxyz ABCXYZ
into       bcdyzA BCDYZa

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

 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

原文由 dawg 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题