【发布时间】:2015-03-27 18:33:14
【问题描述】:
我想用下一个替换字符串的每个字符,最后一个应该成为第一个。这是一个例子:
abcdefghijklmnopqrstuvwxyz
应该变成:
bcdefghijklmnopqrstuvwxyza
是否可以不使用替换功能 26 次?
【问题讨论】:
标签: python
我想用下一个替换字符串的每个字符,最后一个应该成为第一个。这是一个例子:
abcdefghijklmnopqrstuvwxyz
应该变成:
bcdefghijklmnopqrstuvwxyza
是否可以不使用替换功能 26 次?
【问题讨论】:
标签: python
您可以使用str.translate() method 让 Python 一次性将字符替换为其他字符。
使用string.maketrans() function 将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'
【讨论】:
str.replace() 的情况下这样做;不确定在 this 上下文中是否需要它。
当然,只需使用字符串切片:
>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> s[1:] + s[:1]
'bcdefghijklmnopqrstuvwxyza'
基本上,您要做的操作类似于将字符的位置向左旋转一位。所以,我们可以简单地把字符串的第一个字符后面的部分,加上第一个字符。
编辑:我假设 OP 要求旋转一个字符串(从他给定的输入来看这是合理的,输入字符串 有 26 个字符,并且他可能一直在为每个字符进行手动替换),如果帖子是关于创建密码的,请查看上面@Martjin 的答案。
【讨论】:
由于 Python 中的字符串是不可变的,因此您需要将字符串转换为列表、替换,然后再转换回字符串。这里我使用模数。
def convert(text):
lst = list(text)
new_list = [text[i % len(text) +1] for i in lst]
return "".join(new_list)
不要使用切片,因为这样做效率不高。 Python 将为每个更改的字符创建新的完整副本字符串,因为字符串是不可变的。
【讨论】: