On 16Jun2018 12:01, Sharan Basappa <sharan.basa...@gmail.com> wrote:
Is there a difference between these prints. The first one looks a bit complex. 
So, why should it be used?

my_age = 35 # not a lie

print "my age %s." % my_age
print "my age ", my_age

Output:
%run "D:/Projects/Initiatives/machine learning/programs/five.py"
my age 35.
my age  35

In case nobody else notices, the reason the second one has 2 spaces before "35" is that print puts a space between items. So you have a space from the "my age " and also a space from the item separation. The first print statement is only printing one item.

Regarding which style to use: the latter is better because it is more readable. The former can be better when constructing a string with several values where you want more control and better readablility _for the message as a whole_.

Consider:

 # variables, just to make the examples work
 # in a real programme perhaps these came from
 # some more complex earlier stuff
 name = "Sharon"
 age = 35
 print "The person named %r is %d years old." % (name, age)

versus:

 name = "Sharon"
 age = 35
 print "The person named", repr(name), "is", age, "years old."

I'd be inclined to prefer the former one because I can see the shape of the message.

Also, I notice you're using Python 2 (from the print syntax). In Python 3 we have "format strings", which let you write:

 name = "Sharon"
 age = 35
 print(f"The person named {name|r} is {age} years old.")

Win win!

Cheers,
Cameron Simpson <c...@cskk.id.au>
--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to