当打印到控制台时,Python 会将 unicode 值编码为字节。
发送到浏览器时显式编码,直接写入sys.stdout:
#!/usr/bin/python3.2
import sys
out = sys.stdout
out.write(b"Content-Type: text/html; charset=utf8\r\n")
out.write(b"\r\n")
y = "£17"
out.write("Test: {0}\r\n".format(y).encode(encoding='utf8'))
请注意,HTTP 标头应该使用 \r\n(回车,换行)组合,真的。我还添加了用于Content-Type 标头的编码,以便浏览器知道如何再次对其进行解码。
对于 HTML,您确实希望使用 character entity references 而不是 Unicode 代码点:
y = "£17"
out.write("Test: {0}\r\n".format(y).encode(encoding='utf8'))
此时您也可以只使用 ASCII 作为编码。
如果你真的、真的、真的想使用print(),那么用正确的编码重新打开stdout:
utf8stdout = open(1, 'w', encoding='utf-8', closefd=False) # fd 1 is stdout
print("Content-Type: text/html; charset=utf8", end='\r\n', file=utf8stdout)
print("", end='\r\n', file=utf8stdout)
y = "£17"
print("Test:", y, end='\r\n', file=utf8stdout)
您可以使用functools.partial() 稍微简化一下:
from functools import partial
utf8print = partial(print, end='\r\n', file=utf8stdout)
然后使用utf8print() 而不使用额外的关键字:
utf8print("Content-Type: text/html; charset=utf8")
utf8print("")
# etc.
另请参阅Python Unicode HOWTO,了解有关 Python 如何设置输出编码的详细信息,以及有关打印和编码的 this question here on Stack Overflow。