目錄python
程序中常常會出現這樣的 場景:要求用戶輸入信息,而後打印成固定的格式code
好比要求用戶輸入用戶名和年齡,而後打印以下格式:orm
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
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
==比較簡單,實用==string
==f 或者 F==均可以哦it
讓字符和數字可以直接相加哦form
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*******