user2406050
user2406050

Reputation: 13

String formatting unsupported operand

I am trying to create a simple program that prints the day month and year in mm/dd/yy form but I keep getting a trace-back error:

%s/%s/%s
Traceback (most recent call last):
  File "C:/Python34/timenow.py", line 4, in <module>
    print('%s/%s/%s')%(now.month, now.day, now.year)
TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple'

I'm using python 3.4.0

Here's my code:

from datetime import datetime
now = datetime.now()

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

Upvotes: 1

Views: 369

Answers (1)

user2555451
user2555451

Reputation:

You need to place the % operator just after the format string:

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

Your current code has Python trying to use it on the None object returned by print:

>>> type(print('hi'))
hi
<class 'NoneType'>
>>>

Also, I would like to mention two things. The first is that the modern approach for string formatting is to use str.format rather than the % operator:

print('{}/{}/{}'.format(now.month, now.day, now.year))

The second is that string formatting is not strictly needed here because we have the print function's sep parameter, which is used to separate the arguments given to print by a certain string:

>>> from datetime import datetime
>>> now = datetime.now()
>>> print(now.month, now.day, now.year, sep='/')
5/20/2014
>>>

Upvotes: 5

Related Questions