给定以下python脚本:
# dedupe.py
import re
def dedupe_whitespace(s,spacechars='\t '):
"""Merge repeated whitespace characters.
Example:
>>> dedupe_whitespace(r"Green\t\tGround") # doctest: +REPORT_NDIFF
'Green\tGround'
"""
for w in spacechars:
s = re.sub(r"("+w+"+)", w, s)
return s
该函数在python解释器中按预期工作:
$ python
>>> import dedupe
>>> dedupe.dedupe_whitespace('Purple\t\tHaze')
'Purple\tHaze'
>>> print dedupe.dedupe_whitespace('Blue\t\tSky')
Blue Sky
但是,doctest示例失败,因为在与结果字符串进行比较之前,制表符被转换为空格:
>>> import doctest, dedupe
>>> doctest.testmod(dedupe)
给予
Failed example:
dedupe_whitespace(r"Green Ground") #doctest: +REPORT_NDIFF
Differences (ndiff with -expected +actual):
- 'Green Ground'
? -
+ 'Green Ground'
如何在doctest heredoc字符串中编码制表符,以便适当地执行测试结果比较?
是原始的herdoc字符串表示法(
r"""
)实现了这个技巧:我已经使用docstring的文本字符串表示法来实现这一点:
TL;DR:转义反斜杠,即在未修改的字符串中使用
\\n
或\\t
,而不是\n
或\t
您可能不想让docstrings成为原始的,因为这样就无法使用任何Python字符串转义,包括您可能想要的那些转义。
对于支持使用普通转义的方法,只需转义反斜杠字符转义中的反斜杠,以便在Python对其进行解释之后,它会留下一个文本反斜杠,后跟
doctest
可以解析的字符。相关问题 更多 >
编程相关推荐