杰瑞科技汇

怎么在python打出python之禪

在 Python 中打出“Python之禅”(The Zen of Python)非常简单,只需要一行代码。

怎么在python打出python之禪-图1
(图片来源网络,侵删)

最直接的方法

在 Python 的交互式环境(REPL)或任何 Python 脚本中,输入以下代码并按回车:

import this

执行后,你会看到一段优美的文字,这就是“Python之禅”。


示例

在交互式环境中(推荐体验)

打开你的终端或命令行,输入 pythonpython3 进入交互模式,然后直接输入 import this

怎么在python打出python之禪-图2
(图片来源网络,侵删)
$ python
Python 3.9.7 (default, Sep 10 2025, 14:59:43) 
[GCC 11.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
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!
>>>

在 Python 脚本中

你也可以在一个 .py 文件中使用它。

# my_zen.py
import this
# 程序会打印出 Python之禅,然后继续执行
print("This is the end of the script.")

运行这个脚本:

python my_zen.py

输出结果:

怎么在python打出python之禪-图3
(图片来源网络,侵删)
The Zen of Python, by Tim Peters
... (省略中间的诗句) ...
Namespaces are one honking great idea -- let's do more of those!
This is the end of the script.

背后发生了什么?—— 一个有趣的小秘密

import this 的实现方式非常巧妙和有趣,它并不是直接把这段诗作为字符串存储的,如果你好奇,可以看看它的源代码(在 Python 的 this.py 文件中)。

核心原理是:

  1. 加密的字符串:诗的原文被存储在一个名为 s 的字符串中,但这个字符串是经过“编码”的。
  2. 密钥:另一个名为 d 的字符串是解密所需的“密钥”。
  3. 解密过程this.py 脚本会遍历加密的字符串 s 和密钥 d,使用 ord()chr() 函数进行异或(XOR)运算,从而将加密的文本还原成我们看到的优美诗句。

这本身就是对 Python “简洁”和“巧妙”哲学的一个绝佳体现,如果你想深入了解,可以自己搜索 python this.py 的源代码来一探究竟。

要打出“Python之禪”,只需记住:

import this

这是每个 Python 学习者都应该了解的一个小彩蛋,它不仅是代码,更是 Python 编程哲学的精髓。

分享:
扫描分享到社交APP
上一篇
下一篇