str.format简介

一、python的格式化输出
从2.6以后format格式化方法代替了%格式化,%的格式化当然也可以使用,不过建议全部用format。

基本使用例子:
print('hello {}'.format('world'))
>>>hello world

官方文档提供了主要的使用方法:

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

对齐方式:

#{:20}代表了占位20,默认左对齐
#主要的对其方式
^   居中       {:^20}20个占位的中间
<  左对齐      {:<20}强制左对齐 大多数对象的默认值 如string
>  右对齐      {:>20}强制右对齐  number类型的默认值
=  不了解      暂时没用过,不过官方有说明
***
案例:
>>> '{:<30}'.format('left aligned')    #占位30 左对齐
'left aligned                  '
>>> '{:>30}'.format('right aligned')   #占位30 右对齐
'                 right aligned'
>>> '{:^30}'.format('centered')        #占位30中对齐
'           centered           '
>>> '{:*^30}'.format('centered')  # use '*' as a fill char
'***********centered***********'

官方的例子:
1.按位置来访问参数

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')
'a, b, c'
>>> '{}, {}, {}'.format('a', 'b', 'c')  # python3.1+的版本才可以这样用 
'a, b, c'
>>> '{2}, {1}, {0}'.format('a', 'b', 'c')
'c, b, a'
>>> '{2}, {1}, {0}'.format(*'abc')      # 按照你喜欢的位置访问参数
'c, b, a'
>>> '{0}{1}{0}'.format('abra', 'cad')   # 参数可以重复使用
'abracadabra'

2.按照变量来访问参数

>>> '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'

3.时间格式化

>>> import datetime
>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)
>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)
'2010-07-04 12:15:58'

4.其他表示:

#.IP地址转换16进制
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'

综述:记住一般常用的即可

    原文作者:jiandanyaobai
    原文地址: https://www.jianshu.com/p/4783c5e0055b
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞