mpruchni
mpruchni

Reputation: 300

Python New line in return from a function

I am new to python and faced the following problem.. I am trying to get from a function a text in two lines using return, but still getting "\n" as a text (in IDLE 3.5). All works fine when I change "return" to "print", but I need "return".

def myfunc(a):
    text1=["|"]
    i=int(a)
    mystr="abc|"*i+"\n"
    text1.append(mystr)
    text1=''.join(text1)
    b="0"
    text2=[b]
    for b in range(i):
        b+=1
        text2.append("{0:5d}".format(b))
    text1="".join((text1,"".join(text2)))
    return(text1)

result:

>>> myfunc(4)
'|abc|abc|abc|abc|\n0    1    2    3    4'

but

(...)
print(text1)
>>> myfunc(4)
abc|abc|abc|abc|
0    1    2    3    4

Upvotes: 2

Views: 5985

Answers (1)

Sven Marnach
Sven Marnach

Reputation: 601679

When entering an expression that returns a string in the interactive interpreter, you will be shown the representation of that string. This is different from the printing the string, which will write the characters of the string itself directly to the terminal.

The representation generally tries to show the string in a format that Python would accept as a string literal, i.e. it is enclosed in quotes, and special characters are escaped, like you see for \n.

Upvotes: 3

Related Questions