How is python known to add a space between a string literal and a variable?

So I'm currently learning python. 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 curious how this happens. 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 stupid and not very important, but I'm curious, and I hope SO can enlighten me!

+5
source share
3 answers

This is just a cool Python feature.

There are two things that have several arguments: adds the space around the parameters as unclassified and converts each of the arguments into a string separately.

Let's see how simple we can make potentially complex code using the following functions:

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

If we did not have a list of individual parameters, it would look ugly:

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

From Zen Python lines 1 and 3:

Beautiful is better than ugly.

Simple is better than complex.

Check out the Python link for more information.

+1
source

You can easily print without spaces:

 >>> aa = 'abcd' >>> bb = 'efgh' >>> n = 1 >>> print "%s%d%s" % (aa, n, bb) abcd1efgh >>> 
0
source

Nothing smart happens here inside. print always separates its arguments with a space, regardless of who they are.

(Reply ruthlessly stolen from iCodez comment)

0
source

All Articles