Milliways
Milliways

Reputation: 1275

I print a tuple on its own, but not with other variables

I am an experienced c programmer trying to come to terms with Python.

location is tuple and I can print with the following

print(" %s %s" % (date_time, model))
print("Lat: %-.4f, Lon: %-.4f" % (location))

I tried to combine this into a single print, but get error TypeError: must be real number, not tuple with the following

print("%s %s Lat: %-.4f, Lon: %-.4f" % (date_time, model, location))

I have tried several variations, without success.

I can think of several ways of working around this (which I would do if I had to deliver a working program) but would like to understand an elegant method an experienced Python programmer would use.

Upvotes: 2

Views: 358

Answers (2)

timgeb
timgeb

Reputation: 78680

Unpack your tuple.

>>> date_time, model, location = 1, 2, (3, 4)
>>> print("%s %s Lat: %-.4f, Lon: %-.4f" % (date_time, model, *location))
1 2 Lat: 3.0000, Lon: 4.0000

pyformat.info is a helpful site that summarizes string formatting in Python.

In general, I suggest the usage of the new-style str.format over the % operator. Here's the relevant PEP.

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1121654

You want to print the values in the tuple, not the tuple itself. Either concatenate the tuple:

print("%s %s Lat: %-.4f, Lon: %-.4f" % ((date_time, model) + location)))

or interpolate the tuple values into the first tuple:

print("%s %s Lat: %-.4f, Lon: %-.4f" % (date_time, model, *location))

Personally, I'd not use printf formatting here at all. Use the more modern and powerful string formatting syntax, preferably in the form of the (very fast) formatted string literals:

print(f"{date_time} {model} Lat: {location[0]:-.4f}, Lon: {location[1]:-.4f}")

Upvotes: 2

Related Questions