将字符串中的所有字母加1
当我输入 "abc"
时,我希望输出 "bcd"
。
也就是说,我想让字母 A
变成 B
,B
变成 C
,以此类推,一直到 Z
变成 A
。
我该怎么做呢?我一点头绪都没有。
5 个回答
0
编辑:下面的代码只在Python 2中有效,在Python 3中,这个模块叫做str
,而print
是一个函数。
使用maketrans
。以下内容仅适用于小写字母a-z,不包括大写字母A-Z,留给你自己练习:
import string
lowercase_to = string.ascii_lowercase[1:] + string.ascii_lowercase[:1] # bcdefg...xyza
translation = string.maketrans(string.ascii_lowercase, lowercase_to)
s = "abc"
print s.translate(translation) # Prints "bcd"
0
你可以在Python中使用ord
函数来获取一个字符的编码值,然后用chr
函数把这个编码值再转换回字符。对于ASCII字符来说,字母的编码值是连续的,并且按字母顺序排列。例如,ord('a') + 1 == ord('b')
,以此类推。所以你可以像这样做(这里写得比较详细,但其实可以用更简洁的列表推导式来实现):
newstring = ""
for c in "abc":
codepoint = ord(c)
next_codepoint = codepoint + 1
newstring += chr(codepoint)
这就是基本的情况,但你还需要处理从'z'
回绕到'a'
的情况。你可能还需要做一些错误处理,以防某个字符超出了有效范围。你可以这样来处理:
newstring = ""
for c in "abc":
if c == 'z':
newstring += 'a'
elif c == 'Z':
newstring += 'A'
else:
codepoint = ord(c)
if (ord('a') <= codepoint <= ord('z')) or (ord('A') <= codepoint <= ord('Z')):
next_codepoint = codepoint + 1
newstring += chr(codepoint)
else:
raise ValueError("Character %r is outside of the valid range." % c)
3
使用 reduce 方法:
astr = "abc"
print reduce(lambda r,x:r+chr(ord(x)+1),astr,"")
输出结果:
bcd
编辑:
针对特殊情况:
print reduce(lambda r,x:r+chr(ord(x)+1) if x != 'z' else r+'a',astr,"")
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