将字符串中的每个字符更改为字母表中的下一个字符 [英] Change each character in string to the next character in alphabet

查看:99
本文介绍了将字符串中的每个字符更改为字母表中的下一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am coding in Python 2.7 using PyCharm on Ubuntu.

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

I am trying to create a function that will take a string and change each character to the character that would be next in the alphabet.

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

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

When I run the code I get the following error:

/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 行我在做什么?如何在字母表中为每个字符获取以下字符并将其附加到新列表中?

What am I doing wroing in line 11? How can I get the following character in the alphabet for each character and append it to the new list?

非常感谢.

推荐答案

我觉得你把这弄得太复杂了.

I think you are making this too complicated.

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

Just use modulo to roll around to the beginning of the string:

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

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

Which you can reduce to a single unreadable line if you wish:

''.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

如果你希望它被限制为大写小写字母,只需更改导入:

If you want it to be limited to upper of lower case letters, just change the import:

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

这篇关于将字符串中的每个字符更改为字母表中的下一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆