Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python know to add a space between a string literal and a variable?

So I am currently learning python the hard way. In one of the exercises we print string literals with variables between them. I noticed that unlike other languages python automatically adds a space between a string literal and variables. I was just curious as to how it does that. Below is an example of what I mean.

example.py:

total_SO_questions_asked = 1
print "I have asked", total_SO_questions_asked, "question to SO thus far." 

terminal:

$ python example.py
I have asked 1 question to SO thus far.

This is silly and not very important but I am curious, and I am hoping that SO can enlighten me!

like image 738
Oliver Belanger Avatar asked Nov 09 '22 15:11

Oliver Belanger


1 Answers

It's just a cool feature of Python.

There are two things having multiple arguments does: It adds a space around the parameters as necassary, and it converts each of the arguments to a string seperately.

Let's look at how simple we can make potentially complicated code using these features:

a = 5
b = 3
c = a + b
print a, "plus", b, "equals", a+b

If we couldn't have a list of individually casted parameters, it'd look ugly:

print str(a) + " plus " + str(b) + " equals " + str(a+b)

From the Zen of Python, lines 1 and 3:

Beautiful is better than ugly.

Simple is better than complex.

Check out the Python reference for more info.

like image 167
Anubian Noob Avatar answered Nov 14 '22 22:11

Anubian Noob