什么是f-string:
f-string是Python 3.6引入的一种字符串格式化方法。
使用前缀f或F,在字符串中嵌入表达式,用大括号{}括起来。
f-string的优势:
代码简洁,易读性强。
性能优于传统的%格式化和str.format()方法。
基本用法:
name = "Alice"age = 20# 使用f-string格式化字符串message = f"My name is {name}, and I'm {age} years old."print(message) # 输出:My name is Alice, and I'm 20 years old.
表达式求值:
大括号{}内可以是任何有效的Python表达式。
a = 5b = 10print(f"The sum of {a} and {b} is {a + b}.") # 输出:The sum of 5 and 10 is 15.
多行f-string:
使用三引号('''或""")可以创建多行f-string。
name = "Bob"scores = {"math": 90, "english": 85}report = f"""Student Name: {name}Math Score: {scores['math']}English Score: {scores['english']}"""print(report)
格式化数字:
可以在大括号内使用格式说明符来控制数字的显示方式。
pi = 3.1415926print(f"Pi is approximately {pi:.2f}.") # 输出:Pi is approximately 3.14.