gpt4 book ai didi

python - 如何在 Python 文档测试中包含 unicode 字符串?

转载 作者:IT老高 更新时间:2023-10-28 21:01:05 25 4
gpt4 key购买 nike

我正在编写一些必须操作 unicode 字符串的代码。我正在尝试为它编写文档测试,但遇到了麻烦。以下是说明问题的最小示例:

# -*- coding: utf-8 -*-
def mylen(word):
"""
>>> mylen(u"áéíóú")
5
"""
return len(word)

print mylen(u"áéíóú")

首先我们运行代码来查看 print mylen(u"áéíóú") 的预期输出。

$ python mylen.py
5

接下来,我们对其运行 doctest 来查看问题。

$ python -m
5
**********************************************************************
File "mylen.py", line 4, in mylen.mylen
Failed example:
mylen(u"áéíóú")
Expected:
5
Got:
10
**********************************************************************
1 items had failures:
1 of 1 in mylen.mylen
***Test Failed*** 1 failures.

那么我如何测试 mylen(u"áéíóú") 的计算结果为 5?

最佳答案

如果你想要 unicode 字符串,你必须使用 unicode 文档字符串!注意u!

# -*- coding: utf-8 -*-
def mylen(word):
u""" <----- SEE 'u' HERE
>>> mylen(u"áéíóú")
5
"""
return len(word)

print mylen(u"áéíóú")

这将起作用——只要测试通过。对于 Python 2.x,您需要另一个 hack 来使详细的 doctest 模式工作或在测试失败时获得正确的回溯:

if __name__ == "__main__":
import sys
reload(sys)
sys.setdefaultencoding("UTF-8")
import doctest
doctest.testmod()

注意!仅将 setdefaultencoding 用于调试目的。我会接受它用于 doctest,但不会在您的生产代码中的任何地方使用。

关于python - 如何在 Python 文档测试中包含 unicode 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1733414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com