在Python中,占位符是一種用來表示某些值將在后續被替換的特殊標記。占位符通常用于字符串格式化,用來指定在字符串中需要替換的部分。
Python中常見的占位符有以下幾種:
name = "Alice"
age = 25
message = "My name is %s and I am %s years old." % (name, age)
print(message)
輸出:My name is Alice and I am 25 years old.
num1 = 10
num2 = 5
result = "%d + %d = %d" % (num1, num2, num1 + num2)
print(result)
輸出:10 + 5 = 15
pi = 3.14159
message = "The value of pi is approximately %.2f." % pi
print(message)
輸出:The value of pi is approximately 3.14.
percentage = 75
message = "The success rate is %d%%." % percentage
print(message)
輸出:The success rate is 75%.
以上是幾種常見的占位符用法,可以根據具體需求進行靈活運用。