我想用下一个替换字符串的每个字符,而最后一个应该变成第一个。这是一个例子:
abcdefghijklmnopqrstuvwxyz
应该变成:
bcdefghijklmnopqrstuvwxyza
不使用26次替换功能就可以做到吗?
您可以使用该str.translate()
方法一步使Python用其他字符替换字符。
使用该string.maketrans()
功能将ASCII字符映射到其目标;使用string.ascii_lowercase
可以在这里提供帮助,因为这样可以节省您自己键入所有字母的麻烦:
from string import ascii_lowercase
try:
# Python 2
from string import maketrans
except ImportError:
# Python 3 made maketrans a static method
maketrans = str.maketrans
cipher_map = maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[:1])
encrypted = text.translate(cipher_map)
演示:
>>> from string import maketrans
>>> from string import ascii_lowercase
>>> cipher_map = maketrans(ascii_lowercase, ascii_lowercase[1:] + ascii_lowercase[:1])
>>> text = 'the quick brown fox jumped over the lazy dog'
>>> text.translate(cipher_map)
'uif rvjdl cspxo gpy kvnqfe pwfs uif mbaz eph'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句