亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> Python

Python format() 字符串格式化完全指南:占位符、格式化规范、类与字典应用

什么是 Python 字符串 format()?

Python String format() 是用于将占位符替换、替换或转换为有效值的函数。它是 Python 字符串类的内置方法,返回格式化后的字符串。占位符定义在花括号内。

例如:"Welcome to Guru99 {}".format('value here')。

本教程涵盖:

format() 语法

templatestring.format(val1, val2...)

参数

val1, val2 … : 替换模板字符串中花括号 {} 占位符的值。占位符可以是字符串、键值对、整数、浮点数、字符等。

返回值

返回最终字符串,占位符被有效值替换。

占位符形式

模板字符串中用花括号表示占位符,如 {}。占位符可以是空 {},或包含变量如 {name},或数字索引如 {0}、{1} 等。

format() 工作原理

format() 扫描原字符串寻找占位符。占位符可以是空花括号 {},或位置参数如 {0}、{1}。关键字参数时变量名在花括号内如 {name}、{age}。空花括号按序替换 format() 中的值。位置参数索引从 0 开始。关键字参数时,format() 内值的顺序不重要,按变量名匹配替换。

示例:空占位符替换字符串值

字符串有空花括号 {}。format() 给的值替换进花括号。值为字符串。

print("Welcome to {} tutorials".format("Guru99"))

输出:

Welcome to Guru99 tutorials

示例:空占位符替换数值

需在原字符串插入数值。花括号 {} 加在需数值处。执行时空花括号被数值替换。

print("Welcome to Guru{} Tutorials".format("99"))

输出:

Welcome to Guru99 Tutorials

示例:占位符使用变量/关键字参数

可在花括号内使用变量。变量在 format() 中定义,执行时变量值替换进原字符串。

print("Welcome to {name}{num} Tutorials".format(name="Guru", num="99"))

输出:

Welcome to Guru99 Tutorials

示例:占位符使用索引/位置参数

值可用 0、1、2 等索引在占位符中引用。按 format() 中顺序取值。

print("Welcome to {0}{1} Tutorials".format("Guru","99"))

输出:

Welcome to Guru99 Tutorials

示例:字符串中使用多个空占位符

字符串含多个空占位符,每个对应 format() 中的值,第一个值替换第一个占位符,以此类推。

print("{} is {} new kind of {} experience!".format("Guru99", "totally","learning"))

输出:

Guru99 is totally new kind of learning experience!

占位符内格式化

占位符可以是空、变量、索引,还可在占位符内应用 Python 字符串格式化规范。

格式描述示例
:d十进制整数格式print("The binary to decimal value is : {:d}".format(0b0011)) → The binary to decimal value is : 3
:b二进制格式print("The binary value is : {:b}".format(500)) → The binary value is : 111110100
:e科学计数法(小写 e)print("The scientific value is : {:e}".format(40)) → The scientific format value is : 4.000000e+01
:E科学计数法(大写 E)print("The scientific value is : {:E}".format(40)) → The scientific value is : 4.000000E+01
:f定点数(默认 6 位小数)print("The value is : {:f}".format(40)) → The value is : 40.000000;{:.2f} 保留 2 位 → 40.00
:o八进制格式print("The value is : {:o}".format(500)) → The value is : 764
:x十六进制小写print("The value is : {:x}".format(500)) → The value is : 1f4
:X十六进制大写print("The value is : {:X}".format(500)) → The value is : 1F4
:n数字格式(区域感知)print("The value is : {:n}".format(500.00)) → The value is : 500
:%百分比格式(默认 6 位小数)print("The value is : {:%}".format(0.80)) → The value is : 80.000000%;{:.0%} 无小数 → 80%
:_下划线千分位分隔符(Python 3.6+)print("The value is {:_}".format(1000000)) → The value is : 1_000_000
:,逗号千分位分隔符print("The value is : {:,}".format(1000000)) → The value is : 1,000,000
: 正数前加空格print("The value is: {:5}".format(40)) → The value is: 40
:-负数前加减号print("The value is: {:-}".format(-40)) → The value is: -40
:+正数前加加号print("The value is: {:+}".format(40)) → The value is: +40
:=符号靠左对齐print("The value is {:=}".format(-40)) → The value is -40
:^居中对齐print("The value {:^10} is positive value".format(40)) → 居中显示
:>右对齐print("The value {:>10} is positive value".format(40)) → 右对齐
:<左对齐print("The value {:<10} is positive value".format(40)) → 左对齐

配合类使用 format()

创建类并在 format() 中使用类对象。占位符引用类属性或方法。

class MyClass:
    msg1 = "Guru"
    msg2 = "Tutorials"
print("Welcome to {c.msg1}99 {c.msg2}!".format(c=MyClass()))

输出:

Welcome to Guru99 Tutorials!

配合字典使用 format()

也可在 format() 中使用字典:

my_dict = {'msg1': "Welcome", 'msg2': 'Guru99'}
print("{m[msg1]} to {m[msg2]} Tutorials!".format(m=my_dict))

输出:

Welcome to Guru99 Tutorials!

变量替换填充

用 format() 在占位符内添加填充/空格。

print("I have {:5} dogs and {:5} cat".format(2,1))

输出:

I have     2 dogs and     1 cat

也可在占位符用索引如 {0:5}:

print("I have {0:5} dogs and {1:5} cat".format(2,1))

总结

Python

  1. Python print() 函数完全指南:基础用法、空行打印与自定义结束符
  2. Python strip() 方法完全指南:去除首尾空白与自定义字符实战
  3. Python str.count() 完全指南:统计字符与子串出现次数实战
  4. Python 字符串 find() 方法完全指南:语法、参数、替代方案与计数技巧
  5. 精通 Python Lambda 函数:实用示例与最佳实践
  6. Python round() 函数详解与实战示例
  7. 精通 Python map() 函数:语法、示例与最佳实践
  8. Python timeit():精准测量代码执行时间与实战示例
  9. Python collections.Counter:高效计数、更新与算术运算
  10. 理解 Python type() 与 isinstance():实战示例详解
  11. 精通 Java String.indexOf():定位子字符串与实战示例
  12. 精通 Java String compareTo():语法、用例与实战示例