[英]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
. 我是一位经验丰富的
c
程序员,试图熟悉Python
。
location
is tuple
and I can print with the following location
是tuple
,我可以用以下命令打印
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 我试图将其合并到单个打印中,但出现错误
TypeError: must be real number, not tuple
以下内容的TypeError: must be real number, not tuple
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. 我可以想到几种解决此问题的方法(如果必须交付一个有效的程序,我会这样做),但想了解经验丰富的Python程序员会使用的一种优雅方法。
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. pyformat.info是一个有用的网站,总结了Python中的字符串格式。
In general, I suggest the usage of the new-style str.format
over the %
operator. 通常,我建议在
%
运算符上使用新型str.format
。 Here's the relevant PEP. 这是相关的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 . 就个人而言,我不是在这里用printf格式在所有 。 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}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.