How can I include special characters (tab, newline) in a python doctest result string?

后端 未结 6 1491
甜味超标
甜味超标 2021-02-18 19:06

Given the following python script:

# dedupe.py
import re

def dedupe_whitespace(s,spacechars=\'\\t \'):
    \"\"\"Merge repeated whitespace characters.
    Examp         


        
6条回答
  •  离开以前
    2021-02-18 19:44

    It's the raw heredoc string notation (r""") that did the trick:

    # filename: dedupe.py
    import re,doctest
    def dedupe_whitespace(s,spacechars='\t '):
        r"""Merge repeated whitespace characters.
        Example:
        >>> dedupe_whitespace('Black\t\tGround')  #doctest: +REPORT_NDIFF
        'Black\tGround'
        """
        for w in spacechars:
            s = re.sub(r"("+w+"+)", w, s)
        return s
    
    if __name__ == "__main__":
        doctest.testmod()
    

提交回复
热议问题