亚洲区国产区激情区无码区,国产成人mv视频在线观看,国产A毛片AAAAAA,亚洲精品国产首次亮相在线

Python 基礎(chǔ)教程

Python 流程控制

Python 函數(shù)

Python 數(shù)據(jù)類型

Python 文件操作

Python 對象和類

Python 日期和時(shí)間

Python 高級知識

Python 參考手冊

Python format() 使用方法及示例

Python 內(nèi)置函數(shù)

內(nèi)置的format()方法把指定值格式化為指定格式。

format()方法類似于String格式方法。在內(nèi)部,這兩種方法都調(diào)用對象的__format __()方法。

內(nèi)置format()方法是內(nèi)部使用__format __()格式化對象的底層實(shí)現(xiàn),而字符串format()是能夠?qū)Χ鄠€對象字符串執(zhí)行復(fù)雜格式化操作的高級實(shí)現(xiàn)。

format()的語法為:

format(value[, format_spec])

format()參數(shù)

format()方法采用兩個參數(shù):

  • value -需要格式化的值

  • format_spec-有關(guān)如何設(shè)置值格式的規(guī)范。

格式說明符可以采用以下格式:

[[fill]align][sign][#][0][width][,][.precision][type]
where, the options are
fill        ::=  any character
align       ::=  "<" | ">" | "=" | "^"
sign        ::=  "+" | "-" | " "
width       ::=  integer
precision   ::=  integer
type        ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

您可以了解有關(guān)格式類型對齊方式的更多信息。

format()返回值

format()方法把指定值格式化為指定格式。

示例1:使用format()格式化數(shù)字

# d,f和b是類型

# 整數(shù)
print(format(123, "d"))

# 浮點(diǎn)參數(shù)
print(format(123.4567898, "f"))

# 二進(jìn)制參數(shù)
print(format(12, "b"))

運(yùn)行該程序時(shí),輸出為:

123
123.456790
1100

示例2:使用填充,對齊,符號,寬度,精度和類型的數(shù)字格式

# 整數(shù)
print(format(1234, "*>+7,d"))

# 浮點(diǎn)參數(shù)
print(format(123.4567, "^-09.3f"))

運(yùn)行該程序時(shí),輸出為:

*+1,234
0123.4570

在這里,當(dāng)格式化整數(shù)1234時(shí),我們指定了格式化說明符* <+ 7,d。讓我們查看每個選項(xiàng)的意義:

  • * -是填充字符,用于在格式化后填充空白

  • > -這是右對齊選項(xiàng),可將輸出字符串右對齊

  • + -這是一個符號選項(xiàng),用于強(qiáng)制對數(shù)字進(jìn)行簽名(其左側(cè)帶有一個符號)

  • 7-寬度選項(xiàng)可強(qiáng)制數(shù)字采用最小寬度7,其他空格將由填充字符填充

  • , -千位運(yùn)算符在所有千位之間放置逗號。

  • d -它是類型選項(xiàng),用于指定數(shù)字為整數(shù)。

格式化浮點(diǎn)數(shù)123.4567時(shí),我們指定了格式說明符^ -09.3f。這些是:

  • ^ -這是居中對齊選項(xiàng),可將輸出字符串對齊到剩余空間的中心

  • --該符號選項(xiàng)僅強(qiáng)制使用負(fù)數(shù)來顯示符號

  • 0-它是代替空白的字符。

  • 9-使用width選項(xiàng)將數(shù)字的最小寬度設(shè)置為9(包括小數(shù)點(diǎn),千位逗號和符號)

  • .3-精度運(yùn)算符將給定浮點(diǎn)數(shù)的精度設(shè)置為3位

  • f -它是類型選項(xiàng),用于指定數(shù)字為浮點(diǎn)數(shù)。

示例3:通過重寫__format __()使用format()

# 自定義__format __()方法
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return '23'
        return 'None'

print(format(Person(), "age"))

運(yùn)行該程序時(shí),輸出為:

23

在這里,我們重寫了Person類的__format __()方法。

現(xiàn)在,它接受參數(shù)code> age以返回23。如果未指定格式,則返回None。

format()方法在內(nèi)部運(yùn)行Person().__format__("age")返回23。

Python 內(nèi)置函數(shù)