在Python中,可以使用format()
方法來格式化字符串。format()
方法可以在字符串中插入變量或值,并根據(jù)指定的格式進(jìn)行格式化。
具體使用方式如下所示:
{}
作為占位符,然后通過format()
方法傳遞變量或值來替換占位符。name = "Alice"
age = 25
print("My name is {}, and I am {} years old.".format(name, age))
# 輸出:My name is Alice, and I am 25 years old.
format()
方法使用關(guān)鍵字參數(shù)來替換占位符。name = "Bob"
age = 30
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))
# 輸出:My name is Bob, and I am 30 years old.
name = "Charlie"
age = 35
print("My name is {0}, and I am {1} years old.".format(name, age))
# 輸出:My name is Charlie, and I am 35 years old.
pi = 3.14159
print("The value of pi is approximately {:.2f}.".format(pi))
# 輸出:The value of pi is approximately 3.14.
以上是format()
方法的基本用法,還可以使用其他更多的格式化選項來滿足不同的需求。具體可以參考Python官方文檔中的格式化字符串部分:https://docs.python.org/3/library/string.html#format-string-syntax