020 格式化輸出的三種方式

格式化輸出的三種方式

符合某種規範的打印輸出python

1.佔位符

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

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

很明顯,用逗號進行字符串拼接,只能把用戶輸入的名字和年齡放到末尾,沒法放到指定的某個位置,並且數字也必須通過str(數字)的轉換才能與字符串進行拼接,很是麻煩,以下例子字符串

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

上面使用的方法越看越彆扭,越看越麻煩。這就須要用到佔位符。string

如:%s(針對全部數據類型)、%d(僅僅針對數字類型)form

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格式化

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-Strig格式化

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

1.讓字符串和數字能夠直接相加數據類型

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

2.大寫的F也適用。程序

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

age = 19
print(f'{age*2}')
38

3.F-string格式化方法還可直接轉換成浮點型,以及保留幾位小數方法

s1 = 'nick'  # name
s2 = 'ugly'  # qizhi
s3 = 180     # height

print(f'name:{s1}, qizhi:{s2:->10}, height:{s3:.2f}') 
name:nick, qizhi:------ugly, height:180.00
相關文章
相關標籤/搜索