【发布时间】:2014-03-18 13:43:20
【问题描述】:
当我输入"abc" 时,我想得到"bcd" 作为输出。
所以我希望A 成为B 和B 成为C 等等直到Z 这将是A。
那我怎么做呢,我一点头绪都没有。
【问题讨论】:
标签: python string python-3.x
当我输入"abc" 时,我想得到"bcd" 作为输出。
所以我希望A 成为B 和B 成为C 等等直到Z 这将是A。
那我怎么做呢,我一点头绪都没有。
【问题讨论】:
标签: python string python-3.x
您可以使用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
【讨论】:
使用减少:
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,"")
【讨论】:
您可以在 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' 的包装。如果 char 超出有效范围,您可能需要进行一些错误处理。你可以这样做:
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)
【讨论】:
编辑:以下代码仅适用于 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"
【讨论】: