<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

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

          共 4670字,需瀏覽 10分鐘

           ·

          2021-04-23 09:57

          format是字符串內(nèi)嵌的一個方法,用于格式化字符串。以大括號{}來標(biāo)明被替換的字符串,一定程度上與%目的一致。但在某些方面更加的方便

          1、基本用法

          1、按照{(diào)}的順序依次匹配括號中的值

          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、通過索引的方式去匹配參數(shù)

          這里需要注意的是,索引從0開始計算。

          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

          字符串中索引的順序可以打亂,并不影響匹配。

          s = "{1} is a {0}".format('Boy''Tom', )
          print(s) # Tom is a Boy

          3、通過參數(shù)名來匹配參數(shù)

          s = "{name} is a {sex}".format(name='Tom', sex='Boy')
          print(s) # Tom is a Boy

          同理,如果參數(shù)已經(jīng)確定,可以直接利用{}進(jìn)行格式化引用。

          name = 'Tom'
          sex = 'Girl'
          # 以f開頭表示在字符串中支持大括號內(nèi)的python表達(dá)式
          s = f"{name} is a {sex}"
          print(s) # Tom is a Boy

          4、混搭使用

          可以通過索引,參數(shù)名來混搭進(jìn)行匹配。

          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

          需要注意的是,命名參數(shù)必須寫道最后。負(fù)責(zé)會編譯報錯!

          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

          另外,不可以索引和默認(rèn)格式化混合使用。

          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、進(jìn)階用法

          1、支持對參數(shù)部分引用

          可以通過索引對參數(shù)的部分進(jìn)行取值。如下:s[0] = w。

          s = "The word is {s}, {s[0]} is initials".format(s='world')
          # The word is world, w is initials
          print(s)

          2、數(shù)字的處理

          普通的直接匹配數(shù)字沒什么好說的,與基礎(chǔ)部分的字符串匹配一樣。

          s = 'π is {}'.format(3.1415926)
          print(s) # π is 3.1415926

          如何使用format 保留兩位小數(shù)呢?需要使用:.2f,在用%進(jìn)行格式化時我們使用的是%:.2f

          s = 'π is {:.2f}'.format(3.1415926)
          print(s) # π is 3.14

          s1 = 'π is %.2f'3.1415926
          print(s1) # π is 3.14

          同時這種方法還可以用于字符串截取,不過數(shù)字后面就不能加f了。

          s = "{:.1}".format('Hello')
          print(s) # H 

          給數(shù)字加千位符

          s = "{:,}".format(1000000)
          print(s) # 1,000,000

          將數(shù)字轉(zhuǎn)換成二進(jìn)制

          s = "{:b}".format(8)
          print(s) # 1000

          將數(shù)字轉(zhuǎn)換成八進(jìn)制

          s = "{:o}".format(8)
          print(s) # 10

          將數(shù)字轉(zhuǎn)換成十六進(jìn)制

          s = "{:X}".format(12)
          print(s) # C

          總結(jié)如下

          • b: 輸出整數(shù)的二進(jìn)制方式;
          • c: 輸出整數(shù)對應(yīng)的 Unicode 字符;
          • d: 輸出整數(shù)的十進(jìn)制方式;
          • o: 輸出整數(shù)的八進(jìn)制方式;
          • x: 輸出整數(shù)的小寫十六進(jìn)制方式;
          • X: 輸出整數(shù)的大寫十六進(jìn)制方式;

          3、格式處理

          通過:+數(shù)字指定轉(zhuǎn)換后的字符串長度,不足的部分用空格補充

          s = "{:2}b".format('a')
          print(s) # a b  (a后面補了一個空格)
          # 如果指定的長度小于參數(shù)的長度,按照原參數(shù)匹配
          s1 = "{:2}World".format('Hello')
          print(s1) # HelloWorld

          4、字符的填充

          可通過:符號^數(shù)字進(jìn)行字符串的填充。其中數(shù)字為填充后的字符串總長度。

          s = "{:*^10}".format('Hello')
          print(s) # **Hello***

          s = "{:-^20}".format('123456')
          print(s) # -------123456-------

          如果數(shù)字小于字符串的長度,則不進(jìn)行填充操作。

          s = "{:*^3}".format('Hello')
          print(s) # Hello

          5、list、tuple的拆分

          在format格式化時,可使用* 或者 ** 進(jìn)行對list、tuple拆分。

          foods = ['fish''beef''fruit']
          s = 'i like eat {} and {} and {}'.format(*foods)
          # i like eat fish and beef and fruit
          print(s)
          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)
          dict_temp = {'name''Lily''age'18
          # 字典需要用 ** 進(jìn)行拆分
          s = 'My name is {name}, i am {age} years old'.format(**dict_temp)
          print(s) # My name 


          推薦閱讀

          誤執(zhí)行了rm -fr /*之后,除了跑路還能怎么辦?!
          程序員必備58個網(wǎng)站匯總
          大幅提高生產(chǎn)力:你需要了解的十大Jupyter Lab插件

          瀏覽 150
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          評論
          圖片
          表情
          推薦
          點贊
          評論
          收藏
          分享

          手機掃一掃分享

          分享
          舉報
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日本精品视频在线观看 | 影音先锋激情在线 | 中文字幕av一区二区三区 | 亚洲中文在线字幕 | 成人福利免费视频 |