user9993
user9993

Reputation: 6180

Unable to format a string in Python

I get TypeError: not enough arguments for format string for the following code:

 print("%s,%s,%s" % time.strftime("%m/%d/%Y %H:%M:%S"), (sensor.read_temperature(), (sensor.read_humidity()))

It should print the date/time and two variables in CSV format to the console. What's wrong with my format string?

Upvotes: 1

Views: 54

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125078

You only give the format string one argument; the other two values are a separate argument to the print() function.

Move the opening parenthesis:

print("%s,%s,%s" % (
    time.strftime("%m/%d/%Y %H:%M:%S"),
    sensor.read_temperature(),
    sensor.read_humidity())
)

Now all values to be interpolated are in a single tuple, applied to the '...' % portion. You could just use the print() function here though, setting the sep argument to a comma:

print(
    time.strftime("%m/%d/%Y %H:%M:%S"),
    sensor.read_temperature(),
    sensor.read_humidity(),
    sep=',')

Upvotes: 3

Related Questions