string.format
是 Python 中的一個(gè)非常有用的函數(shù),它允許你格式化字符串。在復(fù)雜場(chǎng)景中,這個(gè)函數(shù)可以幫助你插入變量、控制字符串的格式和布局等。以下是一些在復(fù)雜場(chǎng)景中使用 string.format
的示例:
假設(shè)你有三個(gè)變量:name
,age
和 city
,并且你想將它們插入到一個(gè)字符串中。你可以這樣做:
name = "Alice"
age = 30
city = "New York"
formatted_string = "My name is {0}, I am {1} years old, and I live in {2}".format(name, age, city)
print(formatted_string)
輸出:
My name is Alice, I am 30 years old, and I live in New York
有時(shí)你可能希望為字符串中的某些部分指定特定的寬度。例如,你可能希望名字總是有10個(gè)字符寬,無(wú)論它實(shí)際上有多長(zhǎng)。你可以使用 :
來(lái)指定字段寬度:
name = "Alice"
age = 30
city = "New York"
formatted_string = "My name is {:<10}, I am {:>3} years old, and I live in {:<20}".format(name, age, city)
print(formatted_string)
輸出:
My name is Alice , I am 30 years old, and I live in New York
在這個(gè)例子中,<
表示左對(duì)齊,>
表示右對(duì)齊,數(shù)字表示寬度。
string.format
也支持命名字段,這使得代碼更具可讀性。你可以給每個(gè)字段一個(gè)名字,然后在 format
方法中使用這個(gè)名字:
name = "Alice"
age = 30
city = "New York"
formatted_string = "My name is {name}, I am {age} years old, and I live in {city}".format(name=name, age=age, city=city)
print(formatted_string)
輸出與之前的例子相同。
對(duì)于數(shù)字,你可以使用各種格式化選項(xiàng),如小數(shù)點(diǎn)后的位數(shù)、千位分隔符等:
pi = 3.141592653589793
formatted_number = "Pi is approximately equal to {:.2f}".format(pi)
print(formatted_number)
輸出:
Pi is approximately equal to 3.14
在這個(gè)例子中,:.2f
表示保留兩位小數(shù)。
這些只是 string.format
在復(fù)雜場(chǎng)景中的一些應(yīng)用。這個(gè)函數(shù)非常靈活,可以滿(mǎn)足大多數(shù)字符串格式化的需求。