把一个字符串的所有字母加1

2024-04-26 10:00:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我输入"abc"时,我希望得到"bcd"作为输出。在

所以我希望AB,而{}是{},以此类推,直到Z,也就是A。 所以我该怎么做我一点也不知道。在


Tags: abcbcd
3条回答

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

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

使用reduce:

astr = "abc"
print reduce(lambda r,x:r+chr(ord(x)+1),astr,"")

输出:

^{pr2}$

编辑:

对于角盒:

 print reduce(lambda r,x:r+chr(ord(x)+1) if x != 'z' else r+'a',astr,"")

您可以使用^{}函数获取字符的代码点,然后将其递增1,使用^{}函数将其转换回字符。最后,用^{}函数连接所有字符,如下所示

data = "abc"
print("".join(chr(ord(char) + 1) for char in data))
# bcd

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

^{pr2}$

相关问题 更多 >