5.占位符操作

一、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}%")

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值