tags:

views:

1050

answers:

8

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.

+4  A: 

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.

Joachim Sauer
About understanding how to not have \t or whatever when have a multiline comment.
cool-RR
A triple quoted string isn't a multiline comment, it's a raw string, and contains exactly what you type into it.
JimB
I stand corrected.
cool-RR
+1  A: 
def s():
    return 123456

Should do it.

If you are asking how to change strings to integers this is generally done with int(). In this case you would need to strip the new line in the middle. This can be done in different ways, the easiest is:

int("""123
456""".replace('\n', ''))
Lennart Regebro
A: 
re.sub('\D+', '', s)

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

SilentGhost
why the downvote?
SilentGhost
A: 

Try

import re

and then

    return re.sub("\s+", "", s)
Aaron Digulla
A: 

My guess is:

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

Minimum change and does what is asked for.

Juparave
:-) whoever downvoted this has no sense of humor
foosion
Was probably downvoted because the function was supposed to return a string.
recursive
You're right, it probably has to return a string and I returned an integer, anyway I don't get the downvoted thing either, I'm new to python
Juparave
so change the last line to return "123456"
foosion
Now that I re-read the question I know why my answer was downvoted, the question is referring to 'How does Python’s triple-quote string work?' an my answer doesn't comment anything about it
Juparave
+6  A: 
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.

Lorenzo
+1: even though I do not like bashslashes: could use replace('\n','')
van
... and not {{{return s.replace('\n', '')}}}, but rather in the assignment itself: {{{456""".replace('\n', '')}}}
van
+4  A: 

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.

Denis Otkidach
+1 - beat me to it
Paul McGuire
Note to OP - no comma between "123" and "456". The ()'s are there to avoid having to use '\' for line continuations.
Paul McGuire
+1  A: 

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
nosklo