Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why does the console has space when it prints python

Tags:

python

I just noticed something weird

In python, if I do this

>>> k = 1
>>> j = 2
>>> print k,",",j
1 , 2   # prints this

I expected that it would be:

1,2

Why is there a space between these two, whereas

>>> print str(k) + "," + str(j) 
1,2

Thanks

like image 912
frazman Avatar asked Feb 05 '26 10:02

frazman


1 Answers

The first example passes the 3 arguments to print directly, which then converts them to strings and concatenates them together, separated by spaces. The second example first converts and concatenates the string, then passes the entire string to print as a single argument. If you were to do print str(k), ",", str(j) instead, you'd get the same result as the first example.

Think of print in terms of how functions work rather than as a keyword. As an example, take:

def foo(*args):
    return ' '.join(map(str, args))

foo('a', 'b', 'c') will pass foo 3 arguments, and then return those 3 arguments joined by spaces, 'a b c'. foo('a' + 'b' + 'c') will first create the string 'abc', then pass that as a single argument to foo, resulting in foo returning just 'abc'.

like image 95
Silas Ray Avatar answered Feb 07 '26 00:02

Silas Ray



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!