Python 字串格式化

2021-09-08 14:15:17 字數 2222 閱讀 3727

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

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

#

-*- coding: utf-8 -*-

import

unittest

class

stringformattests(unittest.testcase):

deftest_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

" % )

deftest_new_style_format(self):

"""string.format() 提供了新風格的格式化, 語法格式:

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

fill ::= align ::= "<" | ">" | "=" | "^" 對齊方式,分別是左、右、兩邊、中間對齊

sign ::= "+" | "-" | " "

width ::= integer

precision ::= integer

type ::= "b" | "c" | "d" | "e" | "e" | "f" | "f" | "g" | "g" | "n" | "o" | "s" | "x" | "x" | "%" ,預設值是 "s"

詳情參見:

因為{}要作為格式化的標誌位,所以內容盡量不要使用''

另外,可以使用索引

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

:return:

"""print('

hello, , ,

'.format('

a', '

b', 'c'

))

deftest_template(self):

"""這種風格的,可以看作是類似於linux變數風格的

$$var

$$ 代表單個字元 '$'

"""from string import

template

s = template('

$who likes $what')

print(s.substitute(who='

tim', what='

kung pao'))

pass

if__name__ =="

main":

unittest.main()

Python 字串格式化

字串格式化 s 格式化為字串 format hello,s.s enough for ya?values world hot print format values hello,world.hot enough for ya?f 格式化為實數 浮點數 format pi with three dec...

python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...

Python字串格式化

字串的格式化 在python中也有類似於c中的printf 的格式輸出標記。在python中格式化輸出字串使用的是 運算子,通用的形式為 其中,左邊部分的 格式標記字串 可以完全和c中的一致。右邊的 值組 如果有兩個及以上的值則需要用小括號括起來,中間用短號隔開。重點來看左邊的部分。左邊部分的最簡單...