sve*_*ltr 59 python string encoding
我在Python中搜索一个简短而酷的rot13函数;-)我写了这个函数:
def rot13(s):
chars = "abcdefghijklmnopqrstuvwxyz"
trans = chars[13:]+chars[:13]
rot_char = lambda c: trans[chars.find(c)] if chars.find(c)>-1 else c
return ''.join( rot_char(c) for c in s )
Run Code Online (Sandbox Code Playgroud)
谁能让它变得更好?例如,支持大写字符.
Naz*_*san 131
这很简单:
>>> import codecs
>>> codecs.encode('foobar', 'rot_13')
'sbbone'
Run Code Online (Sandbox Code Playgroud)
Pau*_*bel 76
这是一个maketrans/translate解决方案
import string
rot13 = string.maketrans(
"ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz",
"NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm")
string.translate("Hello World!", rot13)
# 'Uryyb Jbeyq!'
Run Code Online (Sandbox Code Playgroud)
Amb*_*ber 65
这适用于Python 2(但不适用于Python 3):
>>> 'foobar'.encode('rot13')
'sbbone'
Run Code Online (Sandbox Code Playgroud)
ars*_*ars 21
该maketrans
和translate
中的功能string
模块时很方便,这种类型的东西.当然,encode
Amber的响应中的方法对于这种特定情况更为方便.
这是一般解决方案:
import string
def make_rot_n(n):
lc = string.ascii_lowercase
uc = string.ascii_uppercase
trans = string.maketrans(lc + uc,
lc[n:] + lc[:n] + uc[n:] + uc[:n])
return lambda s: string.translate(s, trans)
rot13 = make_rot_n(13)
rot13('foobar')
# 'sbbone'
Run Code Online (Sandbox Code Playgroud)
Art*_*par 10
来自模块this.py
(import this
).
d = {}
for c in (65, 97):
for i in range(26):
d[chr(i+c)] = chr((i+13) % 26 + c)
print "".join([d.get(c, c) for c in s])
Run Code Online (Sandbox Code Playgroud)
对于Python 3.1,string.translate
并string.maketrans
不再存在.但是,这些方法可以bytes
代替使用.
因此,最新的解决方案直接受到Paul Rubel的启发,是:
rot13 = bytes.maketrans(
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM")
b'Hello world!'.translate(rot13)
Run Code Online (Sandbox Code Playgroud)
从转换string
到bytes
,反之亦然可以用做encode
和decode
内置函数.
试试这个:
import codecs
codecs.encode("text to be rot13()'ed", "rot_13")
Run Code Online (Sandbox Code Playgroud)
在python-3中,str
@ amber提到的-codec已移至codecs
标准库:
> import codecs
> codecs.encode('foo', 'rot13')
sbb
Run Code Online (Sandbox Code Playgroud)