将字符串的所有字母加1

use*_*744 2 python string python-3.x

当我输入时,"abc"我想得到"bcd"输出.

所以,我想ABBC等高达Z这将是A.那么我该如何做到这一点我没有丝毫的线索.

Ffi*_*ydd 18

您可以使用translate直接将字母更改为其他字母:

try:
    from string import makestrans
except ImportError:
    maketrans = str.maketrans

from string import ascii_lowercase

#old = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
#new = 'bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA'

offset = 1

old_lower = ascii_lowercase
new_lower = old_lower[offset:] + old_lower[:offset]
old = old_lower + old_lower.upper()
new = new_lower + new_lower.upper()

# Create a translate table.
trans = maketrans(old, new)

# Translate your string using trans
print("abc".translate(trans))
# bcd
Run Code Online (Sandbox Code Playgroud)

  • [`new = old [:1] + old [1:]`if only smallcase](http://stackoverflow.com/a/19690385/4279) (2认同)

the*_*eye 5

您可以使用ord函数来获取字符的代码点,然后将其递增1,将其转换回带有chr函数的字符.最后,用str.join函数连接所有字符,就像这样

data = "abc"
print("".join(chr(ord(char) + 1) for char in data))
# bcd
Run Code Online (Sandbox Code Playgroud)

特殊情况z可以像这样处理

print("".join(chr(ord(char) + 1) if char != 'z' else 'a' for char in data))
Run Code Online (Sandbox Code Playgroud)