python格式化字串format函數,python字串format
1. format可以接受無限個的參數,位置可以不按順序:
In [1]: "{} {}".format("hello","world") #不設定位置,按預設順序Out[1]: 'hello world'In [2]: "{0} {1}".format("hello","world") #指定位置Out[2]: 'hello world'In [3]: "{1} {0} {1}".format("hello","world") #指定位置,重複使用參數Out[3]: 'world hello world'In [4]: "{name} {age}".format(name="Linda",age=15)#通過關鍵字Out[4]: 'Linda 15'# 通過字典設定參數In [5]: info = {"name":"Linda","age":15}In [6]: "{name} {age}".format(**info)Out[6]: 'Linda 15'# 通過列表設定參數In [7]: my_list = ['hello','world']In [8]: "{0[0]} {0[1]}".format(my_list)Out[8]: 'hello world'
2. format格式控制:文法是{}中帶冒號(:)
^, <, > 分別是置中、靠左對齊、靠右對齊,後面頻寬度, : 號後面帶填充的字元,只能是一個字元,不指定則預設是用空格填充。
+ 表示在正數前顯示 +,負數前顯示 -; (空格)表示在正數前加空格
b、d、o、x 分別是二進位、十進位、八進位、十六進位。
# 置中顯示,長度度為4In [9]: "{:^4}".format("he")Out[9]: ' he '# 靠左對齊,長度為4,空白地方填充"x"In [10]: "{:x<4}".format("he")Out[10]: 'hexx'# 顯示正負數符號In [11]: "{:+}".format(-3)Out[11]: '-3'# 8的二進位顯示In [12]: "{:b}".format(8)Out[12]: '1000'# 用大括弧{}轉義大括弧In [13]: "{} is {{0}}".format("hello")Out[13]: 'hello is {0}'