python占位符怎样使用
Python 中可使用占位符来替换变量的值,经常使用的占位符有以下几种:
1. %s:用于字符串占位,可以替换任意类型的变量。
2. %d:用于整数占位,只能替换整数类型的变量。
3. %f:用于浮点数占位,只能替换浮点数类型的变量。
4. %x:用于十六进制数占位,只能替换十六进制数类型的变量。
下面是一些使用占位符的示例:
```python
name = "Alice"
age = 25
height = 1.68
# 使用 %s 替换字符串变量
print("My name is %s." % name)
# 使用 %d 替换整数变量
print("I am %d years old." % age)
# 使用 %f 替换浮点数变量
print("My height is %.2f meters." % height)
# 使用 %x 替换十六进制数变量
number = 255
print("The hexadecimal representation of %d is %x." % (number, number))
```
输出结果:
```
My name is Alice.
I am 25 years old.
My height is 1.68 meters.
The hexadecimal representation of 255 is ff.
```
TOP