【问题标题】:Why is the text in this module ROT13 encoded?为什么这个模块中的文本是 ROT13 编码的?
【发布时间】:2018-06-03 07:49:35
【问题描述】:

如果我们打开 Python 解释器并输入import this,您可能知道,它会将 Python 的禅宗打印到控制台中。从 Python source code 这个文本是通过以下代码生成的。

s = """Gur Mra bs Clguba, ol Gvz Crgref

Ornhgvshy vf orggre guna htyl.
Rkcyvpvg vf orggre guna vzcyvpvg.
Fvzcyr vf orggre guna pbzcyrk.
Pbzcyrk vf orggre guna pbzcyvpngrq.
Syng vf orggre guna arfgrq.
Fcnefr vf orggre guna qrafr.
Ernqnovyvgl pbhagf.
Fcrpvny pnfrf nera'g fcrpvny rabhtu gb oernx gur ehyrf.
Nygubhtu cenpgvpnyvgl orngf chevgl.
Reebef fubhyq arire cnff fvyragyl.
Hayrff rkcyvpvgyl fvyraprq.
Va gur snpr bs nzovthvgl, ershfr gur grzcgngvba gb thrff.
Gurer fubhyq or bar-- naq cersrenoyl bayl bar --boivbhf jnl gb qb vg.
Nygubhtu gung jnl znl abg or boivbhf ng svefg hayrff lbh'er Qhgpu.
Abj vf orggre guna arire.
Nygubhtu arire vf bsgra orggre guna *evtug* abj.
Vs gur vzcyrzragngvba vf uneq gb rkcynva, vg'f n onq vqrn.
Vs gur vzcyrzragngvba vf rnfl gb rkcynva, vg znl or n tbbq vqrn.
Anzrfcnprf ner bar ubaxvat terng vqrn -- yrg'f qb zber bs gubfr!"""

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])

我已阅读 What is the source code of the "this" module doing? 从接受的答案中了解到 s 变量文本是 ROT13 编码的,最后 6 行

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])

将通过构建转换表并打印到控制台进行解码。

为什么要编码?也就是说,为什么不这样写:

s = """
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!"""

print(s)

注意:我在 SO 中搜索了类似的问题,但找不到有用的链接。

【问题讨论】:

    标签: python python-3.x encryption cpython


    【解决方案1】:

    来自@abarnert 的comment 说明了一切:

    开玩笑。模块所做的一切,从混淆源 从头开始实现 rot13 的代码,即使它内置于 stdlib,直接违背了Python的禅意。蒂姆·彼得斯也偷偷溜走了 禅宗本身的一些微妙的笑话(注意 TOOWTDI 线有两种不同的方式吗?)

    此外,efforts were made to remove the encoding,但它是rolled back in a subsequent PR

    【讨论】:

      最近更新 更多