Python format 函数:字符串格式化的利器
format 函数是 Python 中用于格式化字符串的内置函数。它的基本用法是通过将值插入到占位符 '{}' 中,然后将其格式化为指定的格式。
具体来说,format 函数可以通过以下方式使用:
- 基本用法:使用占位符 '{}' 将值插入到字符串中,然后使用 format 函数进行格式化。
name = 'Alice'
age = 25
print('My name is {} and I am {} years old.'.format(name, age))
输出:My name is Alice and I am 25 years old.
- 位置参数:可以通过指定占位符的索引来指定要插入的值的位置。
name = 'Bob'
age = 30
print('My name is {1} and I am {0} years old.'.format(age, name))
输出:My name is Bob and I am 30 years old.
- 关键字参数:可以通过指定占位符的名称来指定要插入的值的名称。
name = 'Charlie'
age = 35
print('My name is {name} and I am {age} years old.'.format(name=name, age=age))
输出:My name is Charlie and I am 35 years old.
- 格式化选项:可以在占位符中使用冒号(:)来指定格式化选项,例如指定精度、对齐方式等。
pi = 3.141592653589793
print('The value of pi is approximately {:.2f}.'.format(pi))
输出:The value of pi is approximately 3.14.
- 格式化类型:可以在格式化选项中使用类型代码来指定要格式化的类型,例如整数、浮点数、字符串等。
num = 100
print('The number is {:d}.'.format(num))
输出:The number is 100.
这些是 format 函数的一些常见用法,还有其他更高级的用法,如格式化日期、格式化货币等。详细的用法可以参考 Python 官方文档。
原文地址: https://www.cveoy.top/t/topic/lV27 著作权归作者所有。请勿转载和采集!