Nishant Singh Nishant Singh - 7 months ago 21
Python Question

Python string format error

This is pretty basic:

my_name="nishant"
my_age=24
print "My name is %s"%my_name
print "My age is %d & my name is %s, what are you ?" %(my_age, my_name)


It works fine and prints the intended result, but if I replace the last line as this:

print "My age is %d & my name is %s, what are you ?" %my_age , %my_name


I get this error:

File "my_tests.py", line 7
print "My age is %d & my name is %s, what are you ?" %my_age, %my_name
^
SyntaxError: invalid syntax


My question is :


  1. Why is
    %(my_age, my_name)
    !=
    %my_age , %my_name
    ?

  2. How does Python interpret something like this?


Answer

What's performed by your snippet is binary arithmetic operation, and it require single object as second argument.

With parenthesis, you defining this argument as a two-element tuple. I added additional parenthesis to emphasise how code is interpreted.

print ("My age is %d & my name is %s, what are you ?" % (my_age, my_name))

When not, argument is single element and , %my_name is interpreted as second argument to print statement.

print evaluates each expression in turn and writes the resulting object to standard output

print ("My age is %d & my name is %s, what are you ?" % my_age), (%my_name)

Since %my_name is invalid Python expression, SyntaxError is raised.

Comments