How does Python's triple-quote string work?

后端 未结 9 1072
野性不改
野性不改 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:17

    My guess is:

    def f():
        s = """123
        456"""
        return u'123456'
    

    Minimum change and does what is asked for.

    0 讨论(0)
  • 2020-12-09 08:19

    Maybe I'm missing something obvious but what about this:

    def f():
        s = """123456"""
        return s
    

    or simply this:

    def f():
        s = "123456"
        return s
    

    or even simpler:

    def f():
        return "123456"
    

    If that doesn't answer your question, then please clarify what the question is about.

    0 讨论(0)
  • 2020-12-09 08:27
    def f():
      s = """123\
    456"""
      return s
    

    Don't indent any of the blockquote lines after the first line; end every line except the last with a backslash.

    0 讨论(0)
  • 2020-12-09 08:27
    re.sub('\D+', '', s)
    

    will return a string, if you want an integer, convert this string with int.

    0 讨论(0)
  • 2020-12-09 08:30
    textwrap.dedent("""\
                    123
                    456""")
    

    From the standard library. First "\" is necessary because this function works by removing the common leading whitespace.

    0 讨论(0)
  • 2020-12-09 08:35

    Subsequent strings are concatenated, so you can use:

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

    This will allow you to keep indention as you like.

    0 讨论(0)
提交回复
热议问题