Pythonic way to create a long multi-line string

后端 未结 27 2009
滥情空心
滥情空心 2020-11-22 00:47

I have a very long query. I would like to split it in several lines in Python. A way to do it in JavaScript would be using several sentences and joining them with a +<

27条回答
  •  没有蜡笔的小新
    2020-11-22 01:09

    Others have mentioned the parentheses method already, but I'd like to add that with parentheses, inline comments are allowed.

    Comment on each fragment:

    nursery_rhyme = (
        'Mary had a little lamb,'          # Comments are great!
        'its fleece was white as snow.'
        'And everywhere that Mary went,'
        'her sheep would surely go.'       # What a pesky sheep.
    )
    

    Comment not allowed after continuation:

    When using backslash line continuations (\ ), comments are not allowed. You'll receive a SyntaxError: unexpected character after line continuation character error.

    nursery_rhyme = 'Mary had a little lamb,' \  # These comments
        'its fleece was white as snow.'       \  # are invalid!
        'And everywhere that Mary went,'      \
        'her sheep would surely go.'
    # => SyntaxError: unexpected character after line continuation character
    

    Better comments for Regex strings:

    Based on the example from https://docs.python.org/3/library/re.html#re.VERBOSE,

    a = re.compile(
        r'\d+'  # the integral part
        r'\.'   # the decimal point
        r'\d*'  # some fractional digits
    )
    
    # Using VERBOSE flag, IDE usually can't syntax highight the string comment.
    a = re.compile(r"""\d +  # the integral part
                       \.    # the decimal point
                       \d *  # some fractional digits""", re.X)
    

提交回复
热议问题