1. 程式人生 > >一文秒懂!Python字串格式化之format方法詳解

一文秒懂!Python字串格式化之format方法詳解

format是字串內嵌的一個方法,用於格式化字串。以大括號`{}`來標明被替換的字串,一定程度上與`%`目的一致。但在某些方面更加的方便 ## 1、基本用法 **1、按照{}的順序依次匹配括號中的值** ```python s = "{} is a {}".format('Tom', 'Boy') print(s) # Tom is a Boy s1 = "{} is a {}".format('Tom') # 丟擲異常, Replacement index 1 out of range for positional args tuple print(s1) ``` **2、通過索引的方式去匹配引數** 這裡需要注意的是,索引從0開始計算。 ```python s = "{0} is a {1}".format('Tom', 'Boy') print(s) # Tom is a Boy s1 = "{1} is a {2}".format('Tom', 'Lily', 'Girl') print(s1) # Lily is a Girl ``` 字串中索引的順序可以打亂,並不影響匹配。 ```python s = "{1} is a {0}".format('Boy', 'Tom', ) print(s) # Tom is a Boy ``` **3、通過引數名來匹配引數** ```python s = "{name} is a {sex}".format(name='Tom', sex='Boy') print(s) # Tom is a Boy ``` 同理,如果引數已經確定,可以直接利用{}進行格式化引用。 ```python name = 'Tom' sex = 'Girl' # 以f開頭表示在字串中支援大括號內的python表示式 s = f"{name} is a {sex}" print(s) # Tom is a Boy ``` **4、混搭使用** 可以通過索引,引數名來混搭進行匹配。 ```python s = "My name is {}, i am {age} year old, She name is {}".format('Liming', 'Lily', age=10) print(s) # My name is Liming, i am 10 year old, She name is Lily ``` 需要注意的是,命名引數必須寫道最後。負責會編譯報錯! ```python s = "My name is {}, i am {age} year old, She name is {}".format('Liming', age=10, 'Lily') print(s) # SyntaxError: positional argument follows keyword argument ``` 另外,不可以索引和預設格式化混合使用。 ```python s = "{} is a {0}".format('Boy', 'Tom', ) print(s) s1 = "{} is a {1}".format('Boy', 'Tom', ) print(s1) ``` 以上兩種寫法均報異常。 ``` # ValueError: cannot switch from automatic field numbering to manual field specification ``` ## 2、進階用法 **1、支援對引數部分引用** 可以通過索引對引數的部分進行取值。如下:s[0] = w。 ```python s = "The word is {s}, {s[0]} is initials".format(s='world') # The word is world, w is initials print(s) ``` **2、數字的處理** 普通的直接匹配數字沒什麼好說的,與基礎部分的字串匹配一樣。 ```python s = 'π is {}'.format(3.1415926) print(s) # π is 3.1415926 ``` 如何使用format 保留兩位小數呢? 需要使用`:.2f`,在用%進行格式化時我們使用的是`%:.2f` ```python s = 'π is {:.2f}'.format(3.1415926) print(s) # π is 3.14 s1 = 'π is %.2f'% 3.1415926 print(s1) # π is 3.14 ``` 同時這種方法還可以用於字串擷取,不過數字後面就不能加f了。 ```python s = "{:.1}".format('Hello') print(s) # H ``` **給數字加千位符** ```python s = "{:,}".format(1000000) print(s) # 1,000,000 ``` **將數字轉換成二進位制** ```python s = "{:b}".format(8) print(s) # 1000 ``` **將數字轉換成八進位制** ```python s = "{:o}".format(8) print(s) # 10 ``` **將數字轉換成十六進位制** ```python s = "{:X}".format(12) print(s) # C ``` 總結如下 - b: 輸出整數的二進位制方式; - c: 輸出整數對應的 Unicode 字元; - d: 輸出整數的十進位制方式; - o: 輸出整數的八進位制方式; - x: 輸出整數的小寫十六進位制方式; - X: 輸出整數的大寫十六進位制方式; **3、格式處理** 通過`:+數字`指定轉換後的字串長度,不足的部分用空格補充 ```python s = "{:2}b".format('a') print(s) # a b (a後面補了一個空格) # 如果指定的長度小於引數的長度,按照原引數匹配 s1 = "{:2}World".format('Hello') print(s1) # HelloWorld ``` **4、字元的填充** 可通過`:符號^數字`進行字串的填充。 其中數字為填充後的字串總長度。 ```python s = "{:*^10}".format('Hello') print(s) # **Hello*** s = "{:-^20}".format('123456') print(s) # -------123456------- ``` 如果數字小於字串的長度,則不進行填充操作。 ```python s = "{:*^3}".format('Hello') print(s) # Hello ``` **5、list、tuple的拆分** 在format格式化時,可使用`*` 或者 `**` 進行對list、tuple拆分。 ```python foods = ['fish', 'beef', 'fruit'] s = 'i like eat {} and {} and {}'.format(*foods) # i like eat fish and beef and fruit print(s) ``` ```python foods = ['fish', 'beef', 'fruit'] s = 'i like eat {2} and {0} and {1}'.format(*foods) # i like eat fruit and fish and beef print(s) ``` ```python dict_temp = {'name': 'Lily', 'age': 18} # 字典需要用 ** 進行拆分 s = 'My name is {name}, i am {age} years old'.format(**dict_temp) print(s) # My name is Lily, i am 18 years old ``` --- [史上最全Python資料彙總(長期更新)。隔壁小孩都饞哭了 --- 點選領取 ](https://mp.weixin.qq.com/s/iyr03mVBpy9f6CXWwG4U0A) ![](//p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/7298c5171d604de29abfe748770a96d4~tplv-k3u1fbpfcp-zoom-1