格式化輸出

一、簡單介紹

字符串的格式化輸出目前有兩種方式

  • % 方式(陳舊)
  • str.format() 方式(新式,官方推薦)
  • f-string 方式 (Python3.6 及以上推薦使用)

二、 % 方式

tpl = "i am %s" % "yangge"
print(tpl)

tpl = "i am %s age %d" % ("yangge", 18)
print(tpl)

tpl = "i am %(name)s age %(age)d" % {"name": "yangge", "age": 18}
print(tpl)

tpl = "percent %.2f" % 99.97623
print(tpl)

tpl = "i am %(pp).2f" % {"pp": 123.425556, }
print(tpl)

tpl = "i am %.2f%%" % 123.425556
print(tpl)

更多語法格式


%[(name)][flags][width].[precision]typecode
"""
(name)     可選,用于選擇指定的key
Flags      可選,可供選擇的值有:
   +        右對(duì)齊;正數(shù)前加正號(hào),負(fù)數(shù)前加負(fù)號(hào);
   -        左對(duì)齊;正數(shù)前無符號(hào),負(fù)數(shù)前加負(fù)號(hào);
   空格      右對(duì)齊;正數(shù)前加空格,負(fù)數(shù)前加負(fù)號(hào);
   0        右對(duì)齊;正數(shù)前無符號(hào),負(fù)數(shù)前加負(fù)號(hào);
            用0填充空白處;
width       可選,占有寬度
.precision  可選,小數(shù)點(diǎn)后保留的位數(shù)
typecode    必選
"""

# typecode 有以下這些:
"""
s  獲取傳入對(duì)象的__str__方法的返回值,并將其格式化到指定位置
d  將整數(shù)、浮點(diǎn)數(shù)轉(zhuǎn)換成 十 進(jìn)制表示,并將其格式化到指定位置
f  將整數(shù)、浮點(diǎn)數(shù)轉(zhuǎn)換成浮點(diǎn)數(shù)表示,并將其格式化到指定位置
   (默認(rèn)保留小數(shù)點(diǎn)后6位)
o  將整數(shù)轉(zhuǎn)換成 八  進(jìn)制表示,并將其格式化到指定位置
x  將整數(shù)轉(zhuǎn)換成十六進(jìn)制表示,并將其格式化到指定位置
%  當(dāng)字符串中存在格式化標(biāo)志時(shí),需要用 %%表示一個(gè)百分號(hào)
"""%[(name)][flags][width].[precision]typecode
"""
(name)     可選,用于選擇指定的key
Flags      可選,可供選擇的值有:
   +        右對(duì)齊;正數(shù)前加正號(hào),負(fù)數(shù)前加負(fù)號(hào);
   -        左對(duì)齊;正數(shù)前無符號(hào),負(fù)數(shù)前加負(fù)號(hào);
   空格      右對(duì)齊;正數(shù)前加空格,負(fù)數(shù)前加負(fù)號(hào);
   0        右對(duì)齊;正數(shù)前無符號(hào),負(fù)數(shù)前加負(fù)號(hào);
            用0填充空白處;
width       可選,占有寬度
.precision  可選,小數(shù)點(diǎn)后保留的位數(shù)
typecode    必選
"""

# typecode 有以下這些:
"""
s  獲取傳入對(duì)象的__str__方法的返回值,并將其格式化到指定位置
d  將整數(shù)、浮點(diǎn)數(shù)轉(zhuǎn)換成 十 進(jìn)制表示,并將其格式化到指定位置
f  將整數(shù)、浮點(diǎn)數(shù)轉(zhuǎn)換成浮點(diǎn)數(shù)表示,并將其格式化到指定位置
   (默認(rèn)保留小數(shù)點(diǎn)后6位)
o  將整數(shù)轉(zhuǎn)換成 八  進(jìn)制表示,并將其格式化到指定位置
x  將整數(shù)轉(zhuǎn)換成十六進(jìn)制表示,并將其格式化到指定位置
%  當(dāng)字符串中存在格式化標(biāo)志時(shí),需要用 %%表示一個(gè)百分號(hào)
"""

str.format() 方式

常用示例

tpl = "i am {}, age {}, {}"
r = tpl.format("yangge", 18, 'yangge')
print(r)


tpl = "i am {}, age {}, {}"
r = tpl.format(*["yangge", 18, 'yangge'])
print(r)

a, *b = ["yangge", 18, 'yangge']
print(a)
print(b)
*b, a = ["yangge", 18, 'ge']
print(a)
print(b)

tpl = "i am {0}, age {1}, really {0}"
print(tpl.format("xiguatian", 18))


tpl = "i am {0}, age {1}, really {0}"
tpl.format(*["xiguatian", 18])

tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(name="xiguatian", age=18))
#
tpl = "i am {name}, age {age}, really {name}"
print(tpl.format(**{"name": "xiguatian", "age": 18}))

tpl = "i am {0[0]}, age {0[1]}, really {1[2]}"
print(tpl.format([1, 2, 3], [11, 22, 33]))

tpl = "i am {:s}, age {:d}, money {:f}"
print(tpl.format("seven", 18, 88888.1))

tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl)

tpl = "i am {name:s}, age {age:d}"
tpl.format(name="xiguatian", age=18)

tpl = "i am {name:s}, age {age:d}"
tpl.format(**{"name": "xiguatian", "age": 18})

tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}"
print(tpl.format(15, 15, 15, 15, 15, 15.87623, 2))

tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X},\
      {0:.2%}"
print(tpl.format(15))

tpl = "numbers: {num:b},{num:o},{num:d},{num:x},\
       {num:X}, {num:.2%}"
print(tpl.format(num=15))
print("{0:.3%}".format(0.15))

tpl = "{0:<6}---{0:<8}---{0:>13}"
print(tpl.format('123'))

更多語法格式

[[fill]align][#][0][width][,][.precision][type]

fill 【可選】空白處填充的字符
align  【可選】對(duì)齊方式(需配合width使用)

#            【可選】對(duì)于二進(jìn)制、八進(jìn)制、十六進(jìn)制,如果加上#,
              會(huì)顯示 0b/0o/0x,否則不顯示
              
,           【可選】為數(shù)字添加分隔符,如:1,000,000
width        【可選】格式化位所占寬度
.precision   【可選】小數(shù)位保留精度
type         【可選】格式化類型


"""
    
"""
type  【可選】格式化類型
傳入" 字符串類型 “的參數(shù)
         s,格式化字符串類型數(shù)據(jù)
        空白,未指定類型,則默認(rèn)是None,同s
傳入“ 整數(shù)類型 "的參數(shù)  b,將10進(jìn)制整數(shù)自動(dòng)轉(zhuǎn)換成2進(jìn)制表示然后格式化
  c,將10進(jìn)制整數(shù)自動(dòng)轉(zhuǎn)換為其對(duì)應(yīng)的unicode字符
  d,十進(jìn)制整數(shù)
  o,將10進(jìn)制整數(shù)自動(dòng)轉(zhuǎn)換成8進(jìn)制表示然后格式化;
  x,將10進(jìn)制整數(shù)自動(dòng)轉(zhuǎn)換成16進(jìn)制表示然后格式化(小寫x)
  f , 轉(zhuǎn)換為浮點(diǎn)型(默認(rèn)小數(shù)點(diǎn)后保留6位)表示,然后格式化;
  %,顯示百分比(默認(rèn)顯示小數(shù)點(diǎn)后6位)

三、模板字符串(標(biāo)準(zhǔn)庫)

這是Python中字符串格式化的另一個(gè)工具:模板字符串。它是一種更簡單,功能更少的機(jī)制,但在某些情況下,這可能正是您所需要的。

我們來看一個(gè)簡單的示例:

from string import Template

name = 'shark'

s = Template("hello $name")

print(s.substitute(name=name))

使用模板字符串的最佳時(shí)間是在處理程序用戶生成的格式化字符串時(shí)。由于復(fù)雜性降低,模板字符串是更安全的選擇。

四、 f-string 方式

f-string 也稱為 格式化的字符串文字,是以f或者F 為前綴的字符串文字。

這些字符串可能包含可被替換的字段,這些字段是由{}分隔的表達(dá)式。

雖然其他的字符串文字總是具有常量值,但格式化字符串實(shí)際上是在運(yùn)行時(shí)計(jì)算的表達(dá)式。

語法

name = 'python'
age = 10

s = f'{name},{age}'

print(s)

# 輸出
python,10

任意表達(dá)
f-string 式在運(yùn)行時(shí)計(jì)算的,所以可以在其中放置任何和所有有效的Python表達(dá)式

比如:

>>> f "{2 * 37}" 
'74'

也可以調(diào)用一個(gè)函數(shù)

def flower(inp)
    return inp.flower()

name = "shark"

s = f"{flower(name)} is beautiful"

print(s)
#打印出
shark is beautiful

甚至可以使用從具有 f 字符串的類創(chuàng)建的對(duì)象

class Comedian:
    def __init__(self, first_name, last_name, age):
        self.first_name = first_name
        self.last_name = last_name
        self.age = age

    def __str__(self):
        return f"{self.first_name} {self.last_name} is {self.age}."

    def __repr__(self):
        return f"{self.first_name} {self.last_name} is {self.age}. Surprise!"

可以這樣做

me = Comedian('shark', 'xiguatian', 18)

s = f'{me}'

print(s)

# 打印出
shark xiguatian is 18.

這種情況下需要每行都寫入一個(gè)f
message = (
    f"Hi {name}. "
    "You are a {profession}. "
    "You were in {msg}."
)

使用`"""` 只需要寫入一個(gè)f
message = (
    f"""Hi {name}. 
    You are a {profession}. 
    You were in {msg}."""
)

__str__()__repr__()方法是處理如何呈現(xiàn)對(duì)象為字符串的,所以你需要確保你包括你的類定義這些方法的至少一個(gè)。如果你必須選擇一個(gè),請(qǐng)使用__repr__()它,因?yàn)樗梢杂脕泶?code>__str__()。

默認(rèn)情況下,f-strings將使用__str__(),但__repr__()如果包含轉(zhuǎn)換標(biāo)志,則可以確保它們使用!r

閱讀PEP 8中的縮進(jìn)指南

速度

在運(yùn)行時(shí),花括號(hào)內(nèi)的表達(dá)式在其自己的作用域中計(jì)算,然后與 f-string 的字符串文字部分放在一起。然后返回結(jié)果字符串。

這是一個(gè)速度比較:

>>> import timeit
>>> timeit.timeit("""name = "Eric"
... age = 74
... '%s is %s.' % (name, age)""", number = 10000)
0.003324444866599663

>>> timeit.timeit("""name = "Eric"
... age = 74
... '{} is {}.'.format(name, age)""", number = 10000)
0.004242089427570761

>>> timeit.timeit("""name = "Eric"
... age = 74
... f'{name} is {age}.'""", number = 10000)
0.0024820892040722242

正如你所看到的,f-strings 排在最前面。

然而,情況并非總是如此。當(dāng)它們首次實(shí)施時(shí),它們有一些速度問題str.format() 需要比它更快。引入了一種特殊的BUILD_STRING操作碼

Python f-Strings: 一些細(xì)節(jié)

使用大括號(hào){}在字符串中,必須使用雙括號(hào)

>>> f"{{74}}"
'{74}'

使用三括號(hào)將導(dǎo)致字符串中只有一個(gè)大括號(hào),三個(gè)以上就會(huì)得到更多的大括號(hào)

>>> f"{{{74}}}"
'{74}'

>>> f"{{{{74}}}}"
'{{74}}'


如果您的格式字符串是用戶提供的,要使用模板字符串(#4)來避免安全問題。否則,如果使用的是Python 3.6+,則使用Literal String Interpolation / f-Strings(#3),如果不是,則使用“New Style”str.format(#2)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容