Python字符串格式化str.format()详解:从基础语法到高级应用

Noah
Noah
发布时间:2026-10-13 | 2人浏览过
原创

本文深入解析Python 2.6引入的str.format()字符串格式化方法。详细阐述通过位置参数、关键字参数、对象属性及下标访问数据的多种映射规则,并系统介绍转换类型(!r, !s, !a)、格式限定符(对齐、精度、符号、进制、千位分隔符)及占位符嵌套等高级技巧,帮助开发者掌握高效、灵活的字符串处理方案。

前言

自Python 2.6版本起,语言引入了全新的字符串格式化机制:str.format()。该机制的核心语法利用大括号 {} 和冒号 : 取代了早期版本中使用的 % 符号,提供了更强大且灵活的格式化能力。

格式化时的占位符语法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”规则

通过位置

调用str.format() 时,可以接受任意数量的参数,且参数在格式化字符串中的位置无需按顺序排列:

>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'

通过关键字参数

当使用关键字参数进行格式化时,字符串内部的占位符必须明确指定对应的参数名称:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'

通过对象属性

利用str.format() 可以直接读取并格式化对象的属性值:

>>> class User(object):
...  def __init__(self, name, age):
...   self.name = name
...   self.age = age
...   
...  def __str__(self):
...   return "{self.name}({self.age})".format(self=self)
...  
...  def __repr__(self):
...   return self.__str__()
...  
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'

通过下标

在需要格式化的字符串内部,可以通过下标索引来访问列表或字典中的元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定转化

用户可以指定字符串输出的转化类型:

 conversion ::= "r" | "s" | "a"

其中,"!r" 对应 repr() 函数;"!s" 对应 str() 函数;"!a" 对应 ascii() 函数。具体示例如下:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充与对齐

填充字符通常与对齐方式配合使用。符号 ^、<、> 分别代表居中、左对齐和右对齐,其后跟随目标宽度。冒号 : 后面指定填充字符,该字符必须为单个字符,若未指定则默认使用空格进行填充。

>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'

浮点精度

使用字符 f 表示浮点类型,并可在其前添加精度控制以指定小数位数:

>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'

此外,还可以为浮点数指定符号显示方式:+ 表示正数前显示 + 号,负数前显示 - 号;(空格)表示正数前添加空格,负数前显示 - 号;- 符号与不指定符号(即 {:f})时的效果一致:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'

指定进制

>>> "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位分隔符

可以使用逗号 "," 作为数字的千位分隔符:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

百分数显示

>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'

事实上,format 还支持更多的类型符号:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

其他技巧

占位符嵌套

在某些复杂场景下,占位符的嵌套使用非常实用:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
...  for base in "dXob":
...   print("{0:{width}{base}}".format(num, base=base, width=5), end=' ')
...  print()
...  
...
 5  5  5 101
 6  6  6 110
 7  7  7 111
 8  8 10 1000
 9  9 11 1001
 10  A 12 1010
 11  B 13 1011

作为函数使用

可以先不指定具体的格式化参数,而是将格式化对象作为函数在后续步骤中调用:

>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="suodhuoty@gmail.com"))
Your email address was sudohuoty@gmail.com

转义大括号

当需要在字符串中输出字面量大括号时,可以通过双重大括号进行转义:

>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '

总结

以上就是本文的全部内容,希望这些关于字符串格式化的详细解析能对各位的学习或工作有所帮助。若有任何疑问,欢迎留言交流,感谢大家对本站的支持。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表