python format函数用法

   2025-02-13 4000
核心提示:Python中的format函数是用来格式化输出的,可以将一个字符串中的占位符替换为指定的值。基本用法如下:string.format(value1, va

Python中的format函数是用来格式化输出的,可以将一个字符串中的占位符替换为指定的值。

基本用法如下:

string.format(value1, value2, ...)

其中,string是一个字符串,可以包含一个或多个占位符,占位符用大括号 {} 表示。value1, value2, ... 是要替换占位符的值,可以是任意类型的对象。

例子:

name = "Alice"age = 25print("My name is {} and I'm {} years old.".format(name, age))

输出:

My name is Alice and I'm 25 years old.

在占位符中可以使用一些格式规范来控制输出的样式。常用的格式规范有:

:d:十进制整数:f:浮点数:.2f:保留小数点后两位的浮点数:s:字符串:{length}:指定字符串的最小长度为length,不够时用空格填充:{length}.{precision}:指定浮点数的最小长度为length,并保留小数点后precision

例子:

salary = 10000print("My monthly salary is {:,} dollars.".format(salary))

输出:

My monthly salary is 10,000 dollars.
temperature = 36.6print("Body temperature: {:.1f} °C".format(temperature))

输出:

Body temperature: 36.6 °C

这只是format函数的基本用法和一部分常用的格式规范,实际上format函数还支持更多的功能和格式规范,可以根据需求进行进一步学习和使用。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言