Doctest involving Escape Symbols

There is a fix () function, as an auxiliary function for the output function, which writes lines to a text file.

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 

Turning on the doctrine, I get the following error:

 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') ^ 

No matter what combination I and I use, the teaching does not seem to want to work, although the function itself works fine. You have a suspicion that this is the result of the fact that the teaching is in block commentary, but any tips to eliminate it.

+6
source share
2 answers

Is this what you want?

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

Raw strings are your friend ...

+5
source

Firstly, this is what happens if you really call your function in an interactive interpreter:

 >>> fix("Doug's") "Doug\\'s" 

Note that you do not need to avoid single quotes in double-quoted strings, and that Python does not do this in the representation of the resulting string - only the backslash is reset.

This means that the correct docstring should be (untested!)

 """ returns the corrected line, with all apostrophes prefixed by an escape character >>> fix("DOUG'S") "DOUG\\\\'S" """ 

I would use a string literal for this docstring to make it more readable:

 r""" returns the corrected line, with all apostrophes prefixed by an escape character >>> fix("DOUG'S") "DOUG\\'S" """ 
+1
source

Source: https://habr.com/ru/post/921878/


All Articles