Python的f-string是一种强大的字符串格式化方式,它允许在字符串中直接嵌入表达式。本文将详细介绍f-string的用法和特点。
一、f-string的基本用法 1. 基本语法 1 2 3 4 5 name = "Alice" age = 25 print (f"My name is {name} , and I am {age} years old." )
2. 表达式求值 1 2 3 4 5 6 7 8 9 10 11 12 x = 10 y = 20 print (f"The sum of {x} and {y} is {x + y} ." )def get_greeting (): return "Hello" print (f"{get_greeting()} , world!" )
3. 格式化选项 1 2 3 4 5 6 7 8 9 10 11 12 13 14 pi = 3.1415926535 print (f"Pi is approximately {pi:.2 f} ." ) number = 42 print (f"The number is {number:5d} ." ) print (f"Left-aligned: {number:<10d} " ) print (f"Right-aligned: {number:>10d} " ) print (f"Centered: {number:^10d} " )
二、f-string的高级用法 1. 嵌套f-string 1 2 3 4 5 name = "Alice" age = 25 print (f"{name} is {age} years old, which is {f'{age * 12 } ' } months." )
2. 字典和对象 1 2 3 4 5 6 7 8 9 10 11 12 13 14 person = {"name" : "Alice" , "age" : 25 } print (f"Name: {person['name' ]} , Age: {person['age' ]} " )class Person : def __init__ (self, name, age ): self .name = name self .age = age person = Person("Alice" , 25 ) print (f"Name: {person.name} , Age: {person.age} " )
3. 转义字符 1 2 3 4 5 6 7 8 9 10 11 print (f"{{Hello}} world" )message = f""" Name: {name} Age: {age} Occupation: Programmer """ print (message)
三、f-string与其他格式化方法的对比 1 2 3 4 5 6 7 name = "Alice" age = 25 print ("My name is {}, and I am {} years old." .format (name, age))print (f"My name is {name} , and I am {age} years old." )
2. 与%格式化对比 1 2 3 4 5 6 7 name = "Alice" age = 25 print ("My name is %s, and I am %d years old." % (name, age))print (f"My name is {name} , and I am {age} years old." )
四、f-string的优势
简洁易读 :直接在字符串中嵌入变量和表达式,代码更加简洁易读
表达式求值 :支持在字符串中直接计算表达式
类型转换 :自动处理不同类型的变量,无需手动转换
性能优越 :f-string的性能通常优于其他格式化方法
灵活性高 :支持嵌套、字典访问、对象属性访问等多种操作
五、注意事项 1. 引号使用 1 2 3 print (f"He said, 'Hello!'" )print (f'He said, "Hello!"' )
2. 表达式复杂性 1 2 3 4 5 6 7 print (f"The result is {sum ([x**2 for x in range (100 )])} " )result = sum ([x**2 for x in range (100 )]) print (f"The result is {result} " )
3. 版本兼容性 f-string是在Python 3.6及以上版本引入的,如果需要兼容更早的Python版本,应使用其他格式化方法。
六、综合示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 """ Python f-string格式化字符串综合示例 """ def calculate_area (radius ): """计算圆的面积""" import math return math.pi * radius ** 2 def main (): name = "Alice" age = 25 print (f"=== 基本用法 ===" ) print (f"Name: {name} " ) print (f"Age: {age} " ) print (f"Next year, I'll be {age + 1 } years old." ) print (f"\n=== 数字格式化 ===" ) pi = 3.1415926535 print (f"Pi: {pi:.4 f} " ) print (f"\n=== 宽度和对齐 ===" ) numbers = [1 , 10 , 100 , 1000 ] for num in numbers: print (f"Number: {num:5d} " ) print (f"\n=== 字典和对象 ===" ) person = {"name" : "Bob" , "age" : 30 } print (f"Person: {person['name' ]} , {person['age' ]} " ) print (f"\n=== 调用函数 ===" ) radius = 5 print (f"Area of circle with radius {radius} : {calculate_area(radius):.2 f} " ) if __name__ == "__main__" : main()
七、总结 f-string是Python中一种现代化、简洁且强大的字符串格式化方式,它使得字符串格式化更加直观和易于阅读。通过本文的介绍,你应该已经掌握了f-string的基本用法和高级特性,可以在实际项目中灵活运用它来提高代码的可读性和编写效率。