munchschair
munchschair

Reputation: 1683

Why am I getting this python concatenation error?

I am doing this tutorial and I've run into this weird bug. I am printout the date.

So before the sample codes, you need to have:

from datetime import datetime
now = datetime.now()

this will print

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year)

So will this

print "pizza" + "pie"

so will this

print "%s/%s/%s" % (now.month, now.day, now.year)

But when I introduce concatenating operators:

#Traceback (most recent call last):
#  File "python", line 4, in <module>
#TypeError: not all arguments converted during string formatting
print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

Its some kind of concatenation issue. What I don't understand is that the code will print when I concatenate other strings and when I don't use concatenation with the strings that I want.

Upvotes: 0

Views: 761

Answers (2)

user5119648
user5119648

Reputation:

The problem you're having is caused by operator precedence.

The following line works because this is string literal concatenation, which has a higher precedence than the % operator.

print "%s" "/" "%s" "/" "%s" % (now.month, now.day, now.year)

The following does NOT work because the + operator has a lower precedence than the % operator.

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

To fix it, add parentheses to the concatenation so that it is executed first, like so:

print ("%s" + "/" + "%s" + "/" + "%s") % (now.month, now.day, now.year)

Upvotes: 2

Bryan Oakley
Bryan Oakley

Reputation: 385950

Because this:

print "%s" + "/" + "%s" + "/" + "%s" % (now.month, now.day, now.year)

is the same as this, due to operator precedence (notice the extra parenthesis)

print "%s" + "/" + "%s" + "/" + ("%s" % (now.month, now.day, now.year))

Upvotes: 4

Related Questions