我們的團隊在任何情況下都喜歡使用格式而不是str.format,並且在嘗試學習如何在Python中使用format()時遇到了一些我不知道爲什麼會發生的情況,這是問題:瞭解Python中的格式化功能
3.30以下代碼將顯示什麼? (注意?代表一個空格)
print(format("Welcome", "10s"), end = '#') print(format(111, "4d"), end = '#') print(format(924.656, "3.2f"))
???Welcome#?111#924.66
Welcome#111#924.66
Welcome#111#.66
Welcome???#?111#924.66
,然後回答是4莫名其妙。我覺得默認的對齊是在左側,每種格式,但
print(format("Welcome", "10s"), end = '#')
是左對齊和
print(format(111, "4d"), end = '#')
即someow是右對齊?
所以這是問題所在。
默認情況下,數字是右對齊的,因此數字排隊。其他一切都默認爲左對齊。這在文檔中很明顯。請閱讀它們:https://docs.python.org/3/library/string.html#formatspec – jonrsharpe