python%格式化字符串
时间: 2023-09-11 17:04:04 浏览: 137
在 Python 中,可以使用 `%` 操作符来格式化字符串。其基本语法如下:
```
formatted_string = "format string % (value1, value2, ...)"
```
其中,`format string` 是需要格式化的字符串,`value1, value2, ...` 是需要插入到字符串中的值。在 `format string` 中,可以使用一些占位符来指定插入值的类型和格式,例如:
- `%d`:表示整数类型;
- `%f`:表示浮点数类型;
- `%s`:表示字符串类型;
- `%c`:表示字符类型;
- `%x`:表示十六进制整数类型。
下面是一些示例:
```python
# 整数类型
age = 18
print("My age is %d" % age)
# 浮点数类型
price = 9.99
print("The price is %.2f" % price)
# 字符串类型
name = "Alice"
print("My name is %s" % name)
# 字符类型
first_char = 'A'
print("The first character is %c" % first_char)
# 十六进制整数类型
hex_number = 255
print("The hex number is %x" % hex_number)
```
输出结果:
```
My age is 18
The price is 9.99
My name is Alice
The first character is A
The hex number is ff
```
阅读全文
相关推荐
















