繁体   English   中英

我自己打印一个元组,但不打印其他变量

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

我是一位经验丰富的c程序员,试图熟悉Python

locationtuple ,我可以用以下命令打印

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

我试图将其合并到单个打印中,但出现错误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))

我尝试了几种变体,但没有成功。

我可以想到几种解决此问题的方法(如果必须交付一个有效的程序,我会这样做),但想了解经验丰富的Python程序员会使用的一种优雅方法。

打开元组的包装。

>>> 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是一个有用的网站,总结了Python中的字符串格式。

通常,我建议在%运算符上使用新型str.format 这是相关的PEP。

你想元组,而不是元组本身打印的值。 要么连接元组:

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

或将元组值插值到第一个元组中:

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

就个人而言,我不是在这里用printf格式在所有 使用更现代,更强大的字符串格式语法 ,最好以(非常快) 格式的字符串文字形式使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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