在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%.
以上是几种常见的占位符用法,可以根据具体需求进行灵活运用。