Python中字符串格式化函数Format()的用法详解
发布时间:2023-07-03 05:41:44
Python中字符串格式化函数format()是一种将变量值填充到字符串中的方法,它通过大括号{}来表示占位符,在运行时将占位符替换为变量的值。format()方法可以实现多种格式,包括字符串、数字、浮点数等。下面详细介绍format()函数的用法。
1. 简单的字符串格式化:
可以使用format()函数将变量插入到字符串中,其中{}是占位符。示例:
name = 'Tom'
age = 20
print('My name is {}, and I am {} years old.'.format(name, age))
输出:
My name is Tom, and I am 20 years old.
可以通过大括号{}中的数字指定插入的变量位置,也可以不指定,默认按顺序插入。示例:
name = 'Tom'
age = 20
print('My name is {1}, and I am {0} years old.'.format(age, name))
输出:
My name is Tom, and I am 20 years old.
2. 格式化数字:
可以通过在大括号{}中添加格式控制器来格式化数字。示例:
num = 123.456
print('The number is {:.2f}'.format(num))
输出:
The number is 123.46
可以使用格式控制器来控制数字的小数位数、对齐方式、千位分隔符等。示例:
num1 = 123.456
num2 = 789.123
print('The number 1 is {:0>10.2f}'.format(num1))
print('The number 2 is {:<10,.2f}'.format(num2))
输出:
The number 1 is 000123.46 The number 2 is 789.12
格式控制器的详细用法可以参考Python官方文档。
3. 格式化字符串:
使用format()函数还可以格式化字符串,通过在大括号中指定字符串的长度和对齐方式。示例:
name = 'Tom'
print('My name is {:^10}'.format(name))
输出:
My name is Tom
可以通过格式控制器来指定字符串的长度、对齐方式、填充字符等。示例:
name = 'Tom'
print('My name is {:>>10}'.format(name))
print('My name is {:*<10}'.format(name))
输出:
My name is >>>>>>>Tom My name is Tom*******
4. 嵌套格式化:
可以在format()函数中嵌套使用占位符,将一个格式化部分作为另一个格式化部分的值。示例:
price = 10.5
quantity = 3
total = price * quantity
print('The total price is ${:.2f}, and the quantity is {}'.format(total, quantity))
输出:
The total price is $31.50, and the quantity is 3
在format()函数中,占位符的值可以是一个表达式。示例:
price = 10.5
quantity = 3
total = price * quantity
print('The total price is ${:.2f}, and the quantity is {}'.format(total, quantity + 1))
输出:
The total price is $31.50, and the quantity is 4
5. 使用关键字参数:
可以使用关键字参数向format()函数传递参数值,这样可以在占位符中直接使用关键字。示例:
name = 'Tom'
age = 20
print('My name is {name}, and I am {age} years old.'.format(name=name, age=age))
输出:
My name is Tom, and I am 20 years old.
使用关键字参数可以使代码更具可读性,尤其是在需要传递大量参数的情况下。
以上是format()函数的基本用法和一些高级用法,通过合理使用format()函数可以使代码更简洁、可读性更强。在实际项目中,我们应根据实际情况选择合适的格式化方式。
