How does Python's triple-quote string work?

后端 未结 9 1073
野性不改
野性不改 2020-12-09 08:09

How should this function be changed to return \"123456\"?

def f():
    s = \"\"\"123
    456\"\"\"
    return s

UPDATE: Everyo

相关标签:
9条回答
  • 2020-12-09 08:39

    Try

    import re
    

    and then

        return re.sub("\s+", "", s)
    
    0 讨论(0)
  • 2020-12-09 08:44

    Don't use a triple-quoted string when you don't want extra whitespace, tabs and newlines.

    Use implicit continuation, it's more elegant:

    def f():
        s = ('123'
             '456')
        return s
    
    0 讨论(0)
  • 2020-12-09 08:44

    You might want to check this str.splitlines([keepends])

    Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true.

    Python recognizes "\r", "\n", and "\r\n" as line boundaries for 8-bit strings.

    So, for the problem at hand ... we could do somehting like this..

    >>> s = """123
    ... 456"""
    >>> s
    '123\n456'
    >>> ''.join(s.splitlines())
    '123456'
    
    0 讨论(0)
提交回复
热议问题