目錄
格式化輸出的三種方式
一、占位符(第一種格式化輸出 )(3.0版本使用)
程序中經常會出現這樣的 場景:要求用戶輸入信息,然后打印成固定的格式
比如要求用戶輸入用戶名和年齡,然后打印如下格式:
My name is xxx,my age is xxx.
很明顯用逗號進行字符串拼接,只能把用戶輸入的姓名和年齡放到末尾,無法放到指定的xxx位置,而且數字也必須經過str(數字)的轉換才能與字符串進行拼接。
但是用占位符就很簡單,如:%s(針對所有數據類型),%d(僅僅針對數字類型)
name = 'python'
age = 30
print('My name is %s, my age is %s' % (name, age))
#輸出:
My name is python, my age is 30
age = 30
print(' my age is %s' % age)
#輸出:
my age is 30
二、format格式化(第二種格式化輸出)(3.4版本,具有向上兼容)
name = 'python'
age = 30
print("hello,{},you are {}".format(name,age))
#輸出:
hello,python,you are 30
name = 'python'
age = 30
print("hello,{1},you are {0}-{0}".format(age,name))#索引是根據format后的數據進行的哦
#輸出:
hello,python,you are 30-30
name = 'python'
age = 30
print("hello,{name},you are {age}".format(age=age, name=name))
#輸出:
hello,python,you are 30
三、f-String格式化(第三種格式化輸出)(3.6版本,具有向上兼容)建議使用
比較簡單,實用
f 或者 F都可以哦
讓字符和數字能夠直接相加哦
name = 'python'
age = 30
print(f"hello,{name},you are {age}")
#輸出:
hello,python,you are 30
name = 'python'
age = 30
print(F"hello,{name},you are {age}")
輸出:
hello,python,you are 30
name = 'python'
age = 30
print(F"{age * 2}")
輸出:
60
使打印更加好看
fac = 100.1001
print(f"{fac:.2f}") # 保留小數點后倆位
#保存在*右邊,*20個,fac占8位,剩余在右邊,*可替換
print(f"{fac:*>20}")
print(f"{fac:*<20}")
print(f"{fac:*^20}")
print(f"{fac:*^20.2f}")
#輸出:
100.10
************100.1001
100.1001************
******100.1001******
*******100.10*******