python基礎---->字符串格式化

關於字符串格式化

Python的字符串格式化有兩種方式: %方式、format方式;python

百分號的方式相對來講比較過期,而format方式則是比較先進的方式,企圖替換古老的方式,目前二者並存。spa

一、百分號方式

官方文檔對其說明的格式,更詳細請參考:[PEP-3101]code

%[(name)][flags][width].[precision]typecode

(name)      可選,用於選擇指定的key;
flags          可選;
width         可選,佔有寬度;
.precision   可選,小數點後保留的位數;
typecode    必選;    

百分號格式化經常使用實例:orm

exp = "i am %s" % "clint"
 
exp = "i am %s age %d" % ("clint", 18)
 
exp= "i am %(name)s age %(age)d" % {"name": "clint", "gender": 18}
 
exp = "percent %.2f" % 123.456789
 
exp = "i am %(a).2f" % {"a": 123.4567890, }
 
exp = "i am %.2f %%" % {"a": 123.4567890, }

二、Format方式

[[fill][align][sign][#][0][width][,][.precision][type]

fill           【可選】空白處填充的字符
align        【可選】對齊方式(需配合width使用)
sign         【可選】有無符號數字
#            【可選】對於二進制、八進制、十六進制,若是加上#,會顯示 0b/0o/0x,不然不顯示
,            【可選】爲數字添加分隔符,如:1,000,000
width       【可選】格式化位所佔寬度
.precision 【可選】小數位保留精度
type         【可選】格式化類型

Format格式化經常使用實例:blog

exp = "i am {}, age {}".format("clint", 18)
  
exp  = "i am {}, age {}, {}".format(*["clint", 18, 'clinton])
  
exp = "i am {0}, age {1}, really {0}".format("clint", 18)
  
exp = "i am {0}, age {1}, really {0}".format(*["clint", 18])
  
exp = "i am {name}, age {age}, really {name}".format(name="clint", age=18)
  
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "clint", "age": 18})
  
exp = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
exp = "i am {:s}, age {:d}, money {:f}".format("clint", 18, 88888.1)
  
exp = "i am {:s}, age {:d}".format(*["clint", 18])
  
tpl = "i am {name:s}, age {age:d}".format(name="clint", age=18)
  
exp = "i am {name:s}, age {age:d}".format(**{"name": "clint", "age": 18})
 
exp = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
exp = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
exp = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
exp  = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)
相關文章
相關標籤/搜索