有一个函数fix(),作为输出函数的辅助函数,将字符串写入文本文件。
def fix(line):
"""
returns the corrected line, with all apostrophes prefixed by an escape character
>>> fix('DOUG\'S')
'DOUG\\\'S'
"""
if '\'' in line:
return line.replace('\'', '\\\'')
return line打开doctest,我得到以下错误:
Failed example:
fix('DOUG'S')
Exception raised:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest convert.fix[0]>", line 1
fix('DOUG'S')
^不管我使用\和的哪种组合,doctest似乎都不想工作,即使函数本身工作得很好。我怀疑这是doctest在块注释中的结果,但有任何解决这个问题的提示。
发布于 2012-08-02 02:47:09
这是你想要的吗?
def fix(line):
r"""
returns the corrected line, with all apostrophes prefixed by an escape character
>>> fix("DOUG\'S")
"DOUG\\'S"
>>> fix("DOUG'S") == r"DOUG\'S"
True
>>> fix("DOUG'S")
"DOUG\\'S"
"""
return line.replace("'", r"\'")
import doctest
doctest.testmod()原始字符串是你的朋友..。
发布于 2012-08-02 02:46:52
首先,这是在交互式解释器中实际调用函数时会发生的情况:
>>> fix("Doug's")
"Doug\\'s"请注意,您不需要转义双引号字符串中的单引号,而且Python在结果字符串的表示形式中也不需要转义单引号-只有反斜杠会转义。
这意味着正确的文档字符串应该是(未测试的!)
"""
returns the corrected line, with all apostrophes prefixed by an escape character
>>> fix("DOUG'S")
"DOUG\\\\'S"
"""我会对这个文档字符串使用一个原始的字符串文字,以使其更具可读性:
r"""
returns the corrected line, with all apostrophes prefixed by an escape character
>>> fix("DOUG'S")
"DOUG\\'S"
"""https://stackoverflow.com/questions/11765401
复制相似问题