面试题答案
一键面试理论分析
%
操作符:这是Python早期就存在的格式化方式。它的优点是语法简单,但是在格式化复杂数据结构时不够直观。从性能角度看,%
操作符在格式化时需要解析格式化字符串和参数,在频繁格式化场景下,由于每次都要进行解析操作,性能相对较差。format
方法:它是Python 2.6引入的格式化方式,语法更灵活,支持位置参数、关键字参数等多种方式。在格式化过程中,format
方法同样需要解析格式化字符串,虽然相对%
操作符在功能上有所增强,但性能上并没有质的提升,在频繁格式化时,多次的解析操作也会带来性能损耗。f - string
:这是Python 3.6引入的格式化方式。f - string
在运行时直接将变量值替换到字符串中,而不是像%
操作符和format
方法那样先解析格式化字符串再替换。这使得f - string
在性能上更优,尤其是在频繁格式化的场景下,减少了解析字符串的开销。
代码测试验证思路
import timeit
# 定义一个字典数据
data = {'name': 'John', 'age': 30, 'city': 'New York'}
# 使用%操作符格式化字符串的函数
def format_with_percent():
return '%(name)s is %(age)d years old and lives in %(city)s' % data
# 使用format方法格式化字符串的函数
def format_with_format():
return '{name} is {age} years old and lives in {city}'.format(**data)
# 使用f - string格式化字符串的函数
def format_with_fstring():
return f"{data['name']} is {data['age']} years old and lives in {data['city']}"
# 测试%操作符的性能
time_percent = timeit.timeit(format_with_percent, number = 10000)
# 测试format方法的性能
time_format = timeit.timeit(format_with_format, number = 10000)
# 测试f - string的性能
time_fstring = timeit.timeit(format_with_fstring, number = 10000)
print(f"使用%操作符的时间: {time_percent}")
print(f"使用format方法的时间: {time_format}")
print(f"使用f - string的时间: {time_fstring}")
通过timeit
模块来测试每种格式化方式在多次执行(如10000次)时所花费的时间,从而直观地比较它们的性能。理论上,f - string
花费的时间应该最少,%
操作符和format
方法相对较多。