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

后端 未结 6 1494
甜味超标
甜味超标 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:47

    This is basically YatharhROCK's answer, but a bit more explicit. You can use raw strings or double escaping. But why?

    You need the string literal to contain valid Python code that, when interpreted, is the code you want to run/test. These both work:

    #!/usr/bin/env python
    
    def split_raw(val, sep='\n'):
      r"""Split a string on newlines (by default).
    
      >>> split_raw('alpha\nbeta\ngamma')
      ['alpha', 'beta', 'gamma']
      """
      return val.split(sep)
    
    
    def split_esc(val, sep='\n'):
      """Split a string on newlines (by default).
    
      >>> split_esc('alpha\\nbeta\\ngamma')
      ['alpha', 'beta', 'gamma']
      """
      return val.split(sep)
    
    import doctest
    doctest.testmod()
    

    The effect of using raw strings and the effect of double-escaping (escape the slash) both leaves in the string two characters, the slash and the n. This code is passed to the Python interpreter, which takes "slash then n" to mean "newline character" inside a string literal.

    Use whichever you prefer.

提交回复
热议问题