gpt4 book ai didi

python - 涉及转义字符的 Doctest

转载 作者:太空狗 更新时间:2023-10-29 21:40:34 25 4
gpt4 key购买 nike

有一个函数 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

打开 doctests,我收到以下错误:

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 在 block 评论中的结果,但有解决此问题的任何提示。

最佳答案

这是你想要的吗?

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()

原始字符串是你的 friend ...

关于python - 涉及转义字符的 Doctest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11765401/

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