0
点赞
收藏
分享

微信扫一扫

Python 字符串 ~ 格式化

Python 有两种格式化字符串的方法,即 % 表达式和 format 函数。其中 % 表达式基于 C 语言中的 printf 模型,并在 Python 诞生时就一直存在;format 函数是 Python 2.6Python 3.0 新增内容。

首先,使用 format 函数最简单的例子就是通过参数的位置访问参数。使用 {} 表示占位符,Python 将自动把 format 函数的参数依次传递给 {} 占位符:

>> s = '{} is better than {}.{} is better than {}.'
>> s.format('Beautiful', 'ugly', 'Explicit', 'implicit')
'Beautiful is better than ugly.Explicit is better than implicit.'

也可以使用下标的方式访问 format 参数:

>> s = '{0} is better than {1}.{2} is better than {3}.'
>> s.format('Beautiful', 'ugly', 'Explicit', 'implicit')
'Beautiful is better than ugly.Explicit is better than implicit.'

使用下标访问参数后,每个参数可以出现多次:

>> s = '{0} is better {1} ugly.{2} is better {1} implicit.'
>> s.format('Beautiful', 'than', 'Explicit')
'Beautiful is better than ugly.Explicit is better than implicit.'

除了使用下标访问 format 参数,还可以使用解释性更好的关键字参数的形式:

>> d = {'good1': 'Beautiful', 'bad1': 'ugly', 'good2': 'Explicit', 'bad2': 'implicit', 'than': 'than'}
>> '{good1} is better {than} {bad1}.{good2} is better {than} {bad2}.'.format(**d)
'Beautiful is better than ugly.Explicit is better than implicit.'

此外,占位符 {} 中还可以直接访问对象的属性:

>> from collections import namedtuple
>> Person = namedtuple('Person', 'name, age')
>> alex = Person(name='alex', age=18)
>> '{person.name} is {person.age} years old.'.format(person=alex)
'alex is 18 years old.'

最后,占位符 {} 中还可以添加一个 : 号,并在后面跟上形式化定义的格式。format 形式化定义如下:

  • {:fill}:表示显示时需要填充的字符,默认以空格填充;
  • {:<} {:>} {:^}:表示输出结果的对齐方式,依次为左对齐、右对齐和居中对齐;
  • {:-} {:+}:只在显示数字时生效,即是否显示符号;默认 - 表示只在显示负数时显示符号;
  • {:width}:表示显示的宽度;
  • {:.precision}:表示显示的精度;
  • {:type}:表示显示的类型,取值包含:b c d e E f F g G n o s x X %

示例:

>> from math import pi
>> pi
3.141592653589793
>> '{:.2f}'.format(pi)
'3.14'
>> '{:+.2f}'.format(pi)
'+3.14'
>> '{:10.2f}'.format(pi)
'      3.14'
>> '{:^10.2f}'.format(pi)
'   3.14   '
>> '{:*^10.2f}'.format(pi)
'***3.14***'

此外,还可使用 f'' 的形式,类似于 raw 字符串使用 r'' 定义,来指定 format 格式化字符串。因此上面的例子也可简化为:

>> f'{pi:.2f}'
'3.14'
>> f'{pi:+.2f}'
'+3.14'
>> f'{pi:10.2f}'
'      3.14'
>> f'{pi:^10.2f}'
'   3.14   '
>> f'{pi:*^10.2f}'
'***3.14***'
举报

相关推荐

0 条评论