format函數(shù)在python中的用法

小億
81
2024-09-03 05:45:47

format() 是 Python 中的一個(gè)內(nèi)置函數(shù),用于格式化字符串。它可以接受多種類型的參數(shù),并將它們轉(zhuǎn)換為字符串。format() 函數(shù)的基本語(yǔ)法如下:

format(value, format_spec)

其中,value 是要格式化的值,format_spec 是格式說(shuō)明符,用于指定值的格式。

以下是 format() 函數(shù)的一些常見用法:

  1. 格式化整數(shù)和浮點(diǎn)數(shù):
x = 123456789
formatted_x = format(x, ',')  # 添加千位分隔符
print(formatted_x)  # 輸出:123,456,789

y = 3.14159
formatted_y = format(y, '.2f')  # 保留兩位小數(shù)
print(formatted_y)  # 輸出:3.14
  1. 格式化字符串:
name = "Alice"
age = 30
formatted_string = format("My name is {} and I am {} years old.", name, age)
print(formatted_string)  # 輸出:My name is Alice and I am 30 years old.
  1. 使用格式說(shuō)明符進(jìn)行更復(fù)雜的格式化:
import datetime

now = datetime.datetime.now()
formatted_date = format(now, '%Y-%m-%d %H:%M:%S')  # 格式化日期和時(shí)間
print(formatted_date)  # 輸出:2022-01-01 12:34:56(根據(jù)實(shí)際時(shí)間)

注意:在上面的示例中,我們使用了大括號(hào) {} 作為占位符。這是因?yàn)?format() 函數(shù)支持格式化字符串的新語(yǔ)法,稱為“格式化字符串文字”或“f-string”。在 f-string 中,可以直接在字符串中使用大括號(hào)包圍的變量名,而無(wú)需調(diào)用 format() 函數(shù)。例如:

name = "Alice"
age = 30
formatted_string = f"My name is {name} and I am {age} years old."
print(formatted_string)  # 輸出:My name is Alice and I am 30 years old.

0