共計(jì) 808 個(gè)字符,預(yù)計(jì)需要花費(fèi) 3 分鐘才能閱讀完成。
在 Python 中,可以使用 format 函數(shù)來對(duì)字符串進(jìn)行格式化操作。format 函數(shù)的基本使用方法如下:
- 使用位置參數(shù)進(jìn)行格式化:
name = 'Alice'
age = 25
message = 'My name is {} and I am {} years old.'.format(name, age)
print(message)
輸出:My name is Alice and I am 25 years old.
- 使用關(guān)鍵字參數(shù)進(jìn)行格式化:
name = 'Bob'
age = 30
message = 'My name is {name} and I am {age} years old.'.format(name=name, age=age)
print(message)
輸出:My name is Bob and I am 30 years old.
- 使用位置參數(shù)和關(guān)鍵字參數(shù)混合進(jìn)行格式化:
name = 'Charlie'
age = 35
message = 'My name is {name} and I am {} years old.'.format(age, name=name)
print(message)
輸出:My name is Charlie and I am 35 years old.
- 使用索引進(jìn)行格式化:
name = 'Dave'
age = 40
message = 'My name is {0} and I am {1} years old.'.format(name, age)
print(message)
輸出:My name is Dave and I am 40 years old.
- 使用格式化規(guī)范進(jìn)行格式化:
pi = 3.1415926
message = 'The value of pi is {:.2f}.'.format(pi)
print(message)
輸出:The value of pi is 3.14.
以上只是 format 函數(shù)的一些基本用法,還可以通過 format 函數(shù)進(jìn)行更復(fù)雜的格式化操作,比如對(duì)日期、時(shí)間等進(jìn)行格式化。詳細(xì)的用法可以參考 Python 官方文檔。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完