Python 使用f-string格式化字符串

Python 使用f-string格式化字符串

从3.6版本开始,Python引入了一种新的字符串格式化方法,f-strings或者字面字符串插值。使用这种格式化方法,您可以在字符串常量中嵌入Python表达式。Python的f-strings更快速,更易读,更简洁,并且更不容易出错。

字符串以’f’前缀开头,并插入一个或多个占位符,这些占位符的值是动态填充的。

name = 'Rajesh'
age = 23
fstring = f'My name is {name} and I am {age} years old'
print (fstring)

将会产生以下输出。

My name is Rajesh and I am 23 years old

f-string 可以在 {} 占位符内包含表达式。

price = 10
quantity = 3
fstring = f'Price: {price} Quantity : {quantity} Total : {price*quantity}'
print (fstring)

以下内容将会产生 输出

Price: 10 Quantity : 3 Total : 30

占位符可由字典值填充。

user = {'name': 'Ramesh', 'age': 23}
fstring = f"My name is {user['name']} and I am {user['age']} years old"
print (fstring)

它将产生以下的 输出

My name is Ramesh and I am 23 years old

等号(=)字符用于自我调试f-string表达式。

price = 10
quantity = 3
fstring = f"Total : {price*quantity=}"
print (fstring)

它将产生以下 输出

Total : price*quantity=30

也可以在f-string表达式中调用用户定义的函数。

def total(price, quantity):
   return price*quantity

price = 10
quantity = 3

fstring = f'Price: {price} Quantity : {quantity} Total : {total(price, quantity)}'
print (fstring)

它将产生以下 输出

Price: 10 Quantity : 3 Total : 30

Python的f-strings还支持使用精度规范对浮点数进行格式化,就像format()方法和字符串格式化操作符%一样。

name="Rajesh"
age=23
percent=55.50

fstring = f"My name is {name} and I am {age} years old and I have scored {percent:6.3f} percent marks"
print (fstring)

它将产生以下 输出

My name is Rajesh and I am 23 years old and I have scored 55.500 percent marks

对于字符串变量,您可以像使用 format() 方法和格式化操作符 % 一样指定对齐方式。

name='TutorialsPoint'
fstring = f'Welcome To {name:>20} The largest Tutorials Library'
print (fstring)

fstring = f'Welcome To {name:<20} The largest Tutorials Library'
print (fstring)

fstring = f'Welcome To {name:^20} The largest Tutorials Library'
print (fstring)

它将产生以下 输出

Welcome To       TutorialsPoint The largest Tutorials Library
Welcome To TutorialsPoint       The largest Tutorials Library
Welcome To    TutorialsPoint    The largest Tutorials Library

f-strings可以以十六进制、八进制和科学计数法显示数字。

num= 20
fstring = f'Hexadecimal : {num:x}'
print (fstring)

fstring = f'Octal :{num:o}'
print (fstring)

fstring = f'Scientific notation : {num:e}'
print (fstring)

以下是它将产生的 输出

Hexadecimal : 14
Octal :24
Scientific notation : 2.000000e+01

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程