How does Python's triple-quote string work?

Question:

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

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

UPDATE: Everyone, the question is about understanding how to not have t or whatever when having a multiline comment, not how to use the re module.

Asked By: Ram Rachum

||

Answers:

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.

Answered By: Joachim Sauer
re.sub('D+', '', s)

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

Answered By: SilentGhost

Try

import re

and then

    return re.sub("s+", "", s)
Answered By: Aaron Digulla

My guess is:

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

Minimum change and does what is asked for.

Answered By: Juparave
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.

Answered By: Slumberheart

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.

Answered By: Denis Otkidach

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
Answered By: nosklo
textwrap.dedent("""
                123
                456""")

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

Answered By: claudelepoisson

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 "rn" as line boundaries for 8-bit strings.

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

>>> s = """123
... 456"""
>>> s
'123n456'
>>> ''.join(s.splitlines())
'123456'
Answered By: Rishi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.