python3中format函數(shù)的用法是什么

小億
128
2024-01-29 12:06:40

在Python3中,format()函數(shù)是用于格式化字符串的方法。它可以將變量、常量或表達(dá)式的值插入到字符串中的特定位置。

format()函數(shù)的用法有兩種形式:

  1. 位置參數(shù)形式:

    "字符串{}".format(值)
    

    這種形式使用占位符{}來(lái)標(biāo)識(shí)要插入的值的位置,然后通過format()函數(shù)的參數(shù)按位置將值插入到對(duì)應(yīng)位置。

  2. 關(guān)鍵字參數(shù)形式:

    "字符串{關(guān)鍵字}".format(關(guān)鍵字=值)
    

    這種形式使用占位符{關(guān)鍵字}來(lái)標(biāo)識(shí)要插入的值的位置,然后通過format()函數(shù)的關(guān)鍵字參數(shù)將值插入到對(duì)應(yīng)位置。

以下是一些示例:

name = "Alice"
age = 25

# 位置參數(shù)形式
print("My name is {}, and I am {} years old.".format(name, age))

# 關(guān)鍵字參數(shù)形式
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))

輸出:

My name is Alice, and I am 25 years old.
My name is Alice, and I am 25 years old.

除了使用位置參數(shù)和關(guān)鍵字參數(shù)外,format()函數(shù)還支持其他的格式化選項(xiàng),如指定數(shù)值的精度、填充字符、對(duì)齊方式等。詳細(xì)的格式化選項(xiàng)可以參考Python官方文檔中的字符串格式化部分。

0