[英]I print a tuple on its own, but not with other variables
我是一位經驗豐富的c
程序員,試圖熟悉Python
。
location
是tuple
,我可以用以下命令打印
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.