格式化輸出的三種方式

1、佔位符

程序中常常會有這樣場景:要求用戶輸入信息,而後打印成固定的格式spa

好比要求用戶輸入用戶名和年齡,而後打印以下格式:My name is xxx,my age is xxx.code

很明顯,用逗號進行字符串拼接,只能把用戶輸入的名字和年齡放到末尾,沒法放到指定的xxx位置,並且數字也必須通過str(數字)的轉換才能與字符串進行拼接,很是之麻煩,咱們來試一試。orm

age = 19
print('My name is xxx,my age is '+str(age))
My name is xxx,my age is 19
age = 19
print('My name is xxx,my age is', age)
My name is xxx,my age is 19
name = 'nick'
age = 19
print('My name is '+name+' my age is '+str(age))
My name is nick my age is 19

上面使用的方法越看越彆扭,越看越麻煩。這就須要用到佔位符,如:%s(針對全部數據類型)、%d(僅僅針對數字類型)字符串

name = 'nick'
age = 19
print('my name is %s my age is %s' % (name, age))
my name is nick my age is 19
age = 19
print('my age is %d' % age)
my age is 19

2、format格式化

講真,很雞肋的格式化的方法,若是你須要使用這個,遇到多參數的時候,仍是須要在句子後面噼裏啪啦傳上一大堆參數。使用這個不如用佔位符或下面的f-String格式化。string

name = 'nick'
age = 19
print("Hello, {}. You are {}.".format(name, age))
Hello, nick. You are 19.
name = 'nick'
age = 19
print("Hello, {1}. You are {0}-{0}.".format(age, name))
Hello, nick. You are 19-19.
name = 'nick'
age = 19
print("Hello, {name}. You are {age}-{age}.".format(age=age, name=name))
Hello, nick. You are 19-19.

3、f-String格式化

相比較佔位符的方式,python3.6版本新增了f-String格式化的方式,比較簡單易懂,這是目前我用的最多的方式,推薦使用這種方式。it

name = "nick"
age = 19
print(f"Hello, {name}. You are {age}.")
Hello, nick. You are 19.

大寫的F也適用。form

name = "nick"
age = 19
print(F"Hello, {name}. You are {age}.")
Hello, nick. You are 19.
age = 19
print(f'{age*2}')
38

再給你秀個之後可能會用到的操做。class

salary = 6.6666
print(f'{salary:.2f}')
6.67
相關文章
相關標籤/搜索