「Python教案」字符串格式化操作
课程目标
1.知识目标
- 能够正确使用%、str.format()以及f-string进行数据格式化。
- 能够分析不同格式化方法的适用场景及优缺点等。
- 能够利用格式化控制符,例如对齐、宽度、精度、进制转换等进行格式化控制。
2.能力目标
- 能够根据需求选择合适的字符串格式化方法,编写高效、可维护的代码。
- 能够调试并解决格式化操作中的常见错误,例如参数不匹配、转义冲突等。
3.思政目标
- 根据代码规范性与可读性要求,培养严谨细致的工匠精神。
- 结合实际案例,强化“技术服务于社会”的职业责任感。
教学内容
1.字符串格式化概念
字符串格式化是将变量或值插入到字符串中的过程。
2.三种格式化方法
(1)%格式化
(2)str.format()
(3)f-string
3.格式化控制符
格式化控制允许将精确控制变量在字符串中的显示方式,包括数字精度、对齐、填充等。
重点分析
难点分析
教学活动设计
概念引入
1.字符串格式化概念
字符串格式化就好比“填空题”,预先写好模板,动态填入答案。
示例:
# 模板:姓名:___,年龄:___岁
name = "张三"
age = 20
print(f"姓名:{name},年龄:{age}岁") # 输出:姓名:张三,年龄:20岁
字符串格式化是将变量或值插入到字符串中的过程。
2.三种格式化方法
- %格式化
name = "Alice"
age = 25
print("Hello, %s. You are %d years old." % (name, age)) # 输出:Hello, Alice. You are 25 years old.
常用格式说明符:
- %s:字符串
- %d:十进制整数
- %f:浮点数
- %x:十六进制整数
- str.format()
name = "Alice"
age = 25
print("Hello, {}. You are {} years old.".format(name, age)) # 输出:Hello, Alice. You are 25 years old.
print("Hello, {1}. You are {0} years old.".format(age, name)) # 输出:Hello, Alice. You are 25 years old.
print("Hello, {name}. You are {age} years old.".format(name="Alice", age=25)) # 输出:Hello, Alice. You are 25 years old.
- f-string
name = "Alice"
age = 25
print(f"Hello, {name}. You are {age} years old.") # 输出:Hello, Alice. You are 25 years old.
print(f"Next year you will be {age + 1} years old.") # 输出:Next year you will be 26 years old.
f-strings特点:
- 在字符串前加f或F
- 可以直接在花括号内写表达式
- 执行速度快,可读性好
3.格式化控制符
格式化控制允许将精确控制变量在字符串中的显示方式,包括数字精度、对齐、填充等。
- 浮点精度控制
pi = 3.1415926535
# 保留2位小数
print(f"Pi: {pi:.2f}") # 输出: Pi: 3.14
# 保留4位小数
print(f"Pi: {pi:.4f}") # 输出: Pi: 3.1416
- 整数格式化
number = 42
# 十进制
print(f"Decimal: {number:d}") # 输出: Decimal: 42
# 二进制
print(f"Binary: {number:b}") # 输出: Binary: 101010
# 十六进制
print(f"Hex: {number:x}") # 输出: Hex: 2a
# 八进制
print(f"Octal: {number:o}") # 输出: Octal: 52
- 对齐与填充
text = "Hello"
number = 123
# 右对齐,宽度10,用空格填充
print(f"'{text:>10}'") # 输出: ' Hello'
# 左对齐,宽度10
print(f"'{text:<10}'") # 输出: 'Hello '
# 居中对齐,宽度10
print(f"'{text:^10}'") # 输出: ' Hello '
# 用特定字符填充
print(f"'{text:*^10}'") # 输出: '**Hello***'
print(f"'{number:0>6}'") # 输出: '000123'
- 千位分隔符
large_number = 1234567890
print(f"{large_number:,}") # 输出: 1,234,567,890
- 百分比显示
ratio = 0.756
print(f"{ratio:.1%}") # 输出: 75.6%
- 科学计数法
small_number = 0.000000123
print(f"{small_number:.2e}") # 输出: 1.23e-07
- 日期时间格式化
from datetime import datetime
now = datetime.now()
# 日期格式化
print(f"{now:%Y-%m-%d}") # 输出:2025-06-01
print(f"{now:%H:%M:%S}") # 输出: 11:31:32
print(f"{now:%A, %B %d, %Y}") # 输出: Sunday, June 01, 2025
- 嵌套格式化
width = 10
precision = 2
value = 12.34567
print(f"{value:{width}.{precision}f}") # 输出: ' 12.35'
- 符号显示
positive = 123
negative = -123
print(f"{positive:+}") # 输出: +123
print(f"{negative:+}") # 输出: -123
print(f"{positive: }") # 输出: ' 123' (正数前加空格)
- 数字进制前缀
print(f"{42:#b}") # 输出: 0b101010
print(f"{42:#x}") # 输出: 0x2a
print(f"{42:#o}") # 输出: 0o52
案例解析
案例:生成工资条
name = "Charlie"
basic_salary = 12000
bonus = 3000
total = basic_salary + bonus
print(f"{'Name':<10}{'Basic':>10}{'Bonus':>10}{'Total':>10}")
print(f"{name:<10}{basic_salary:>10}{bonus:>10}{total:>10.2f}")
运行结果
Name Basic Bonus Total
Charlie 12000 3000 15000.00
常见错误
错误:%格式化中参数顺序错误。
# 错误:参数顺序与%符号不匹配
print("Name: %s, Age: %d" % (25, "Alice")) # 报错
# 正确:参数顺序需一致
print("Name: %s, Age: %d" % ("Alice", 25))
错误:f-string中直接调用函数(需提前计算)。
# 错误:f-string中直接调用耗时函数import time
print(f"Current time: {time.sleep(1)}") # 阻塞1秒,无返回值
# 正确:提前计算结果
current_time = time.time()
print(f"Current time: {current_time}")
运行结果
Current time: None
Current time: 1748790701.306868
课堂练习
练习:格式化输出学生信息(姓名、学号、成绩,成绩保留1位小数)。
name = "王五"
student_id = "2023001"
score = 88.75
print(f"姓名:{name},学号:{student_id},成绩:{score:.1f}")
运行结果
姓名:王五,学号:2023001,成绩:88.8
练习:生成表格(姓名左对齐,工资右对齐,宽度10)。
name = "赵六"
salary = 12000.5
print(f"{'姓名':<10}{'工资':>10}") # 表头
print(f"{name:<10}{salary:>10.2f}") # 数据行
运行结果
姓名 工资
赵六 12000.50
练习:生成百分比字符串(如"Completion: 75.00%")。
progress = 0.75
print(f"Completion: {progress * 100:.2f}%")
运行结果
Completion: 75.00%
课后作业
作业:编写程序,输入商品名称、单价、数量,输出格式化的小票(总价保留2位小数)。
product = "笔记本"
price = 39.99
quantity = 2
total = price * quantity
print(f"商品:{product},单价:{price:.2f},数量:{quantity},总价:{total:.2f}")
运行结果
商品:笔记本,单价:39.99,数量:2,总价:79.98
考核设计
1.过程性考核(40%)
- 课堂练习的完成程度(20%)
- 编写代码的规范性与添加注释的规范性(10%)
- 参与小组讨论和解决问题的能力(10%)
2.终结性考核(60%)
- 理论测试(20%):
- 综合项目(40%):
理论测试:
填空题:f"Value: {3.14159:.2f}"中,.2f表示______。
答案:保留2位小数。
选择题:以下哪种方法性能最高?
A.%格式化 B.str.format() C.f-string
答案:C
简答题:简述str.format()与f-string的适用场景。
答案:str.format()适用于兼容旧版Python或动态字段名;f-string适用于Python 3.6+且追求性能与可读性。
综合项目:
编写程序,已知商品名称为"Apple"、单价为5.99、数量为3,输出格式化的小票(总价保留2位小数)。
输出结果:
Product: Apple, Price: 5.99, Quantity: 3, Total: 17.97
参考答案:
product = "Apple"
price = 5.99
quantity = 3
total = price * quantity
print(f"Product: {product}, Price: {price:.2f}, Quantity: {quantity}, Total: {total:.2f}")