Python學習 :格式化輸出
- 2020 年 1 月 19 日
- 筆記
方式一:使用佔位符 %
常用佔位符:% s (s = string 字元串) % d (d = digit 整數(十進位)) % f ( f = float 浮點數)
name = input("請輸入你的名字:") age = input("請輸入你的年齡:") job = input("請輸入你的職業:") salary = input("請輸入你的薪酬:") if salary.isdigit(): #輸入的數據是否像數字 salary = int(salary) else : exit("請輸入正確的數字") # 如果輸入的不是數字將會退出程式 # ''' 三引號可以用於插入數據 info = ''' ---------- info of %s ---------- 姓名:%s 年齡:%s 職業:%s 薪酬:%s ------------------------------- ''' % (name, name, age, job, salary) print(info)方式二:format()函數(推薦使用)
format()函數通過傳入的字元串作為參數,並使用{}大括弧作為佔位符
format(a , b) 變數a 對應{0} 變數b 對應{1}
注意:Python從0開始計數,意味著索引中的第一位是0,第二位是1
位置的匹配: (1)不帶編號,即「{}」 (2)帶數字編號,可調換順序,即「{0}」、「{1}」 (3)帶關鍵字,即「{a}」、「{b}」(需要設置關鍵字對應的字元串)
age = 20 name = 'ALEX' print('{1} is {0} years old' .format(age,name)) print('{b} is {a} years old' .format(a = age, b = name)) >>> ALEX is 20 years old ALEX is 20 years oldformat()可以指定格式,讓輸出的結果符合指定的樣式
一些符號的含義:
{0} —— { 0 } 表示第一個位置
{0:10} —— { :10} 表示有10個字元那麼長並且左對齊(默認為左對齊)
{0:>15} ——{ :>15} 表示有15個字元那麼長並且右對齊
{0:.2} ——{ : .2} 表示對於傳入的字元串,截取前兩個字元
{0:^} —— {: ^} 表示放到該位置的字元串要居中
{0:d} —— {0:d} 表示需要在這個位置放一個整數(數字默認狀態下為右對齊)
{0:f} —— {0:f} 表示需要在這個位置放一個浮點數(數字默認狀態下為右對齊)
a = " I love {0:10} and {1:10}. ".format("sing","dance") # 左對齊,字元串的長度為10個字元 print(a) >>> I love sing and dance . a = " I love {0:^10.3} and {1:^10.3}. ".format("sing","dance") # 居中,字元串的長度為10個字元,截取前三個字元 print(a) >>> I love sin and dan . age = 28 weight = 70.423 print("Alex is {0} years old and his weights is {1:.2f} kg." . format(age,weight)) # 浮點數需要保留兩位小數 >>> Alex is 28 years old and his weights is 70.42 kg.
