简体   繁体   中英

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.

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.

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}")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM