python的輸出——print的不同形式總結

在python3中,使用print有不同的形式,總結如下:

1. print(str1, str2, str3…)或print(str1+str2+str3…)
這是最簡單的一種輸出方式,也比較容易理解,這樣的輸出形式得到的結果會是由str1、str2、str3…拼接成的一個長字符串。兩者的不同之處如下:

str_1 = 'today is'
str_2 = 'a good day.'
str_3 = 'I am very happy!'
#輸出:today is a good day. I am very happy!(各字符串之間有空格)
print(str_1, str_2, str_3)
#輸出:today isa good day.I am very happy!(各字符串之間無空格)
print(str_1 + str_2 + str_3)

2. format()
一種比較常見的格式化輸出方式。其格式爲:

print("{要輸出的內容將在此處顯示}".format(要輸出的內容))
  • 輸出字符串:
# 輸出:Alice and Zoey are good friends.
print("{} and {} are good friends.".format("Alice", "Zoey"))

# 在括號中的數字用於指向傳入對象在 format()中的位置
# 輸出:Zoey and Alice are good friends.
print("{1} and {0} are good friends.".format("Alice", "Zoey"))

# format() 可以使用關鍵字參數
# 輸出:Bob and Tina are couples.
print("{boy} and {girl} are couples.".format(boy='Bob', girl='Tina'))

  • 輸出其他格式:
# 格式化輸出
# 1.!a——使用ascii函數(判斷參數是不是在ASCII碼錶中)
char = '哈哈哈'
# 輸出:轉換後的結果是:'\u54c8\u54c8\u54c8'
print("轉換後的結果是:{!a}".format(char))
# 2.!s——使用str
num = 123
# 報錯:此時num爲int型
print(num + ",hello")
# 不會報錯,輸出:123,hello
print("{!s}".format(num) + ",hello")
# 3.":.Nf"——保留N位小數
float_num = 1.234567
# 輸出:保留三位小數的結果是:1.235
print("保留三位小數的結果是:{:.3f}".format(float_num))

3. %
%是一種比較舊的輸出方式,使用%佔位,在%後的內容用於填充,具體用法如下:

  • 輸出字符串
# 使用%s輸出字符串:Nicky is learning music.
print('%s is learning %s.' % ("Nicky", "music"))
  • 輸出數字
# 使用%d輸出整數:The number is 54.
num = 54
print("The number is %d." % num)
# 使用%.Nf輸出N位小數:The value is rounded to three decimal places is 2.444.
float_num = 2.444444
print("The value is rounded to three decimal places is %.3f." % float_num)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章