一、str='Hello, %s' % 'world'
执行结果:Hello, world
1、%s 是文本格式化占位符
- %d:整数
- %f:浮点数
- %x:十六进制数
- %o:八进制数
2、%
- 字符串格式化运算符
- 用于连接字符串模板和要插入的值
二、print('%2d-%02d' % (3, 1)) 打印结果: 3-01
1、%2d:
- %:格式化符号
- 2:表示占位符的宽度为2个字符
- d:表示整型
2、%02d:
- %:表示格式化符号
- 0:表示用0填充
- 2:表示站位符长度2
- d:表示整型
常用示例
# 1. 字符串编码解码示例
# 使用 decode 解码字节串,errors="ignore" 忽略无法解码的字符
chinese_bytes = b"\xe4\xb8\xad\xff"
print(chinese_bytes.decode("utf-8", errors="ignore"))
# 计算字节串长度
chinese_text = b"\xe4\xb8\xad\xe6\x96\x87"
print(f"字节串长度: {len(chinese_text)}")
print()
# 2. 字符串格式化示例
# 2.1 基本格式化
message = "Hello, %s" % "world"
print(message)
# 2.2 多参数格式化
message = "Hello, %s, %s" % ("world", "china")
print(message)
# 2.3 命名参数格式化
message = "Hello, %(name)s, %(age)d" % {"name": "world", "age": 20}
print(message)
# 2.4 简单命名参数格式化
message = "Hello %(name)s" % {"name": "dch"}
print(message)
# 3. 数字格式化示例
# 3.1 整数格式化
print("%2d-%02d" % (3, 1)) # 输出: " 3-01"
# 3.2 浮点数格式化
print("%.2f" % 3.1415926) # 输出: "3.14"
# 3.3 f-string 格式化
radius = 1234
area = 3.1415926
print(f"The area of a circle with radius {radius} is {area:.2f}")
# 4. 百分比计算示例
score1 = 72
score2 = 85
improvement = ((score2 - score1) / score1 * 100)
print(f"成绩提高了 {improvement:.1f}%")