Python:字串格式化

FangJinuo發表於2018-09-19

Python中提供了多種格式化字串的方式,遇到一個專案,在一個檔案中,就用了至少兩種方式。特別是在使用Log時,更讓人迷惑。

因此特地花時間來了解一下Python中字串格式化的幾種方式:

# -*- coding: utf-8 -*-

import unittest
class StringFormatTests(unittest.TestCase):
    def test_C_style(self):
        """
            % 是老風格的字串格式化方式, 也稱為C語言風格,語法如下:
                %[(name)][flags][width].[precision]type
            name: 是佔位符名稱
            flags: 可取值有:
                - 左對齊(預設右對齊)
                0 表示使用0填充(預設填充是空格)
            width:  表示顯示寬度
            precision:表示精度,即小數點後面的位數
            type:
                %s string,採用str()顯示
                %r string,採用repr()顯示
                %c char
                %b 二進位制整數
                %d, %i 十進位制整數
                %o 八進位制整數
                %x 十六進位制整數
                %e 指數
                %E 指數
                %f, %F 浮點數
                %% 代表字元‘%’

            注意,如果內容中包括%,需要使用%%來替換
        :return:
        """
        # 測試 flag 與 width
        print("%-10x" % 20)
        print("%-10x" % 20)
        print("%10x" % 20)
        print("%010x" % 20)

        # 測試 name的用法:
        print("hello, %s, my name is %s, age is %d" % ("lucy", "zhangsan", 20))
        print("hello, %(yname)s, my name is %(myname)s, age is %(myage)d" % {"yname":"lucy", "myname":"zhangsan", "myage":20})

    def test_new_style_format(self):
        """
        string.format() 提供了新風格的格式化, 語法格式:{:format_spec}
        format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]
            fill        ::=  <any character>
            align       ::=  "<" | ">" | "=" | "^" 對齊方式,分別是左、右、兩邊、中間對齊
            sign        ::=  "+" | "-" | " "
            width       ::=  integer
            precision   ::=  integer
            type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"  ,預設值是 "s"

        詳情參見:https://docs.python.org/2/library/string.html

        因為{}要作為格式化的標誌位,所以內容儘量不要使用`{`或`}`
        另外,可以使用索引

        相比而言,新風格的比老風格的強大太多了。

        :return:
        """
        print(`hello, {0}, {2}, {1}`.format(`a`, `b`, `c`))

    def test_template(self):
        """這種風格的,可以看作是類似於Linux變數風格的
            ${var}
            $var
            $$ 代表單個字元 `$`
        """
        from string import Template
        s = Template(`$who likes $what`)
        print(s.substitute(who=`tim`, what=`kung pao`))
        pass

if __name__ =="main":
    unittest.main()

 

相關文章