在Python中,占位符主要用于格式化字符串,它们允许你在字符串中插入变量值。以下是一些常用的占位符及其用法:
-
%d
- 整数占位符
print("I scored %d points." % 20)
-
%f
- 浮点数占位符
print("The answer is approximately %.2f." % 3.1415926)
-
%s
- 字符串占位符
print("Hello, my name is %s." % "Alice")
-
%x
- 十六进制整数占位符
print("The hexadecimal value of 255 is %x." % 255)
-
%c
- 单个字符占位符
print("The Unicode value of 'A' is %c." % 'A')
-
%o
- 八进制整数占位符
print("The octal value of 10 is %o." % 10)
-
%e
- 科学计数法表示的浮点数
print("The value of pi is approximately %e." % 3.141592653589793)
-
%g
- 自动选择表示方式(浮点数或科学计数法)
print("The value is %g." % 1.23456789e+10)
-
.format()
方法
name = "Alice"
age = 25
print("My name is {}, and I am {} years old.".format(name, age))
- f-string(Python 3.6+)
name = "Bob"
age = 30
print(f"My name is {name}, and I am {age} years old.")
使用占位符时,你可以指定宽度、精度和对齐方式,例如:
print("{:<10} {:>10} {:<10}".format("Left", "Right", "Center"))
以上代码将输出:
Left Right Center