Python输出格式化 格式化字符串语法 format f-string 格式化操作符% 数据类型转换 对齐方式 转换标志字符

本文介绍了Python中三种主要的字符串格式化方法:使用`.format()`,f-string(格式化字符串文字)以及%操作符。详细讲解了各个方法的语法,包括格式对齐、转换标志字符、数字进制转换等内容,为Python字符串格式化提供全面指南。
摘要由CSDN通过智能技术生成

Python输出格式化 格式化字符串语法

1.format

1.1 Format String Syntax

格式字符串语法 str.format() 方法和 Formatter 类共享相同的格式字符串语法(尽管在 Formatter 的情况下,子类可以定义自己的格式字符串语法)。 语法与格式化字符串文字的语法有关,但存在差异。

格式字符串包含用大括号 {}包围的“替换字段”。 大括号中未包含的任何内容都被视为文字文本,将原样复制到输出中。 如果需要在文字文本中包含大括号字符,可以通过加倍转义:{ { }}

替换字段的语法如下:

replacement_field ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name        ::=  arg_name ("." attribute_name | "[" element_index "]")*
arg_name          ::=  [identifier | digit+]
attribute_name    ::=  identifier
element_index     ::=  digit+ | index_string
index_string      ::=  <any source character except "]"> +
conversion        ::=  "r" | "s" | "a"
format_spec       ::=  <described in the next section>

用不太正式的术语来说,替换字段可以以 field_name 开头,它指定要对其值进行格式化并插入到输出中的对象,而不是替换字段。 field_name后跟可选的转换字段,前面是感叹号“!”,和 format_spec,前面是冒号“:”。 这些指定替换值的非默认格式。

field_name本身以一个 arg_name开头,它可以是数字或关键字。 如果是数字,则表示位置参数,如果是关键字,则表示命名关键字参数。 如果格式字符串中的数字 arg_names依次为 0, 1, 2, … ,它们都可以省略(不仅仅是一些),并且数字 0, 1, 2, … 将按该顺序自动插入。 由于 arg_name不是引号分隔的,因此无法在格式字符串中指定任意字典键(例如,字符串'10'':-]')。 arg_name后面可以跟任意数量的索引或属性表达式。 '.name' 形式的表达式使用 getattr()选择命名属性,而'[index]'形式的表达式使用__getitem__()进行索引查找。

  • str.format() 可以省略位置参数说明符,因此 '{}{}'.format(a, b) 等效于'{0} {1}'.format(a, b) )Formatter可以省略位置参数说明符。

一些简单的格式字符串示例:

"First, thou shalt count to {0}"  # 引用第一个位置参数
"Bring me a {}"                   # 隐式引用第一个位置参数
"From {} to {}"                   # 与“From {0} to {1}”相同
"My quest is {name}"              # 引用关键字参数 'name' 
"Weight in tons {0.weight}"       # 第一个位置参数的“weight”属性
"Units destroyed: {players[0]}"   # 关键字参数“players”的第一个元素。
>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated
'abracadabra'
>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')
'Coordinates: 37.24N, -115.81W'
>>> coord = {
   'latitude': '37.24N', 'longitude': '-115.81W'}
>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)
'Coordinates: 37.24N, -115.81W'
>>> coord = (3, 5)
>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)
'X: 3;  Y: 5'
>>> c = 3-5j
>>> ('The complex number {0} is formed from the real part {0.real} and the imaginary part {0.imag}.').format(c
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SK Primin

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值