共計(jì) 402 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中,可以使用兩種方法來實(shí)現(xiàn)字符串占位符的替換。
方法一:使用百分號(hào)占位符
name = "John"
age = 25
print("My name is %s and I am %d years old." % (name, age))
輸出結(jié)果:My name is John and I am 25 years old.
在上面的示例中,%s 表示字符串占位符,%d 表示整數(shù)占位符。使用 % 后面的括號(hào)傳入變量值進(jìn)行替換。
方法二:使用 format() 方法
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))
輸出結(jié)果:My name is John and I am 25 years old.
在上面的示例中,{} 表示占位符,使用 format() 方法傳入變量值進(jìn)行替換。
這兩種方法都可以用于替換字符串中的占位符,你可以根據(jù)自己的喜好選擇其中一種使用。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完