format 用法

本文根据官方文档及自己理解整理,只整理出自己可以理解的部分,h因个人水平有限,难免有所错误和纰漏,欢迎批评指正。

格式{ [field_name] ["!" conversion] [":" format_spec] }

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

大括号的内容大概分为两部分,冒号":"前的部分和后面的部分。里面的参数全部都可以省略。

冒号前部分主要为数据引用转化部分

冒号后面为指定详细的显示格式(format specification)

冒号前部分

冒号前的部分,分两块,一块为field_name,另一块为使用叹号"!"开头conversion(指定函数转化)

field_name

field_name可以有以下几种方式:

常规:

1.指定索引

2.省略,什么也不写,默认为其在字符串中的位置索引,从0开始。

3.标识符

复杂:

  1. 指定索引或标识符的前提下,使用其attribute_name(属性名) 比如point.x;0.name等方式
  2. 指定索引或标识符的前提下,使用其element_index(索引),比如lst[2];0[0]等
>>> "Hello,My name is {},I'm {}.".format('Wesley','12')
"Hello,My name is Wesley,I'm 12."

>>> "Hello,My name is {0},I'm {1}.".format('Wesley','12')
"Hello,My name is Wesley,I'm 12."

>>> "Hello,My name is {name},I'm {age}.".format(age='12',name='Wesley')
"Hello,My name is Wesley,I'm 12."

比较复杂一些

>>> "Hello,My name is {0[0]},I'm {0[1]}.".format(youth)
"Hello,My name is Wesley,I'm 12."

>>> "Hello,My name is {boy[0]},I'm {boy[1]}.".format(boy=youth)
"Hello,My name is Wesley,I'm 12."

>>> from collections import namedtuple
>>> Person=namedtuple("Persion",['name','age'])
>>> boy = Person('Wesley',12)

>>> "Hello,My name is {0.name},I'm {0.age}.".format(boy)
"Hello,My name is Wesley,I'm 12."

>>> "Hello,My name is {boy.name},I'm {boy.age}.".format(boy=boy)
"Hello,My name is Wesley,I'm 12.

conversion部分

conversion部分:

  • !s 调用函数str()
  • !r 调用函数repr()
  • !a 调用函数ascii()

对传进来的数值使用format函数之前,首先使用指定的函数对其进行强制类型转换为str类型。str(),repr()和ascii()三个函数转换为字符串的方式有所不同。若省略,则由__format__函数自动处理。

冒号后部分

format_spec语法

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill            ::=  <any character>
align           ::=  "<" | ">" | "=" | "^"
sign            ::=  "+" | "-" | " "
width           ::=  digit+
grouping_option ::=  "_" | ","
precision       ::=  digit+
type            ::=  "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

format_spec对于不同类型的数值,其支持的参数不同。

字符串

format specification中,很多方法只支持数字,相对来说,对数值做字符串处理,主要支持以下:

  • 宽度,width : 用数字标识
  • 对齐 align: 对字符串分别用'<' '^' '>' 标识 左对齐 居中 右对齐
  • 填充 fill : 用指定字符填充空白位,默认为空格

对齐填充和宽度

字符串,默认左对齐,默认填充为空格;

都可以省略,可以指定对齐方式,填充省略,默认为空格。

若要修改填充,必须指定对齐方式

对齐分三种,左对齐('<'),右对齐('>'),居中('^')

>>> '{:}'.format("hello")
'hello'

指定宽度为10个字符,默认为左对齐

>>> '{:10}'.format("hello")
'hello     '

指定宽度为10个字符,右对齐

>>> '{:>10}'.format("hello")
'     hello'

指定宽度为10个字符,居中对齐,空白字符用“*”填充

>>> '{:*^10}'.format("hello")
'**hello***'

若填充为0,还可以在宽度前加一个数字0,字符串格式同样遵循指定对齐方式

指定宽度为10个字符,居中对齐,空白字符用“0”填充。

>>> '{:^010}'.format("hello")
'00hello000'

字符串各种不怎么用前导0做填充,这个主要给数字格式用的,其默认的对齐方式为‘=’,只能在数字格式中使用的对齐方式)

>>> '{:010}'.format("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: '=' alignment not allowed in string format specifier

数字类型

format specification中,对于数字类型,同样有宽度,填充和对齐方式选项,相对于字符串,数字类型还支持:

  • sing 控制符 ’+‘ ’-‘ ’和space
  • 进制转换
  • 小数位控制
  • 前导0
  • 第四种对齐方式‘=’

sing位

数字专用,sign 位置在对齐align后面,#、前导0或宽度前面;

sign 正数3.14 负数3.14
“+” 不显示符号“3.14” 显示负号(-)“-3.14”
“-” 显示正号(+)“+3.14” 显示负号(-)“-3.14”
空格 前面有个空格“ 3.14” 显示负号(-)“-3.14”

进制转换和井号

花括号内最右边的字段type,用来指这个数据如何被显示出来。对整数来说,可以指定type很多,如下表:

Type Meaning
'b' Binary format. Outputs the number in base 2. 二进制
'c' Character. Converts the integer to the corresponding unicode character before printing.字符
'd' Decimal Integer. Outputs the number in base 10. 默认,十进制
'o' Octal format. Outputs the number in base 8.八进制
'x' Hex format. Outputs the number in base 16, using lower- case letters for the digits above 9.小写16进制
'X' Hex format. Outputs the number in base 16, using upper- case letters for the digits above 9.大写16进制
'n' Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.
None The same as 'd'.

>>> '{:}'.format(97)
'97'
>>> '{:d}'.format(97)
'97'
>>> '{:n}'.format(97)
'97'
>>> '{:b}'.format(97)
'1100001'
>>> '{:o}'.format(97)
'141'
>>> '{:x}'.format(97)
'61'
>>> '{:c}'.format(97)
'a'
>>> '{:x}'.format(0x61)
'61'

井号#用来显示数字的前缀

>>> '{:#b}'.format(97)
'0b1100001'
>>> '{:#x}'.format(97)
'0x61'

来个组合的,显示97的二进制形式,显示正负号,指定宽度为20,居中对齐,填充@

>>> '{:@^+#20b}'.format(97)
'@@@@@+0b1100001@@@@@'

小数点精度

对于小数位,type位有很多,我就能看懂f e 和 %,只用过f和%,别的还没用过。

type 'f', 将数字表示为小数部分,默认为6位小数点;超位舍弃,"四舍六入五取偶"的方式舍弃

>>> '{:f}'.format(122)
'122.000000'
>>> '{:f}'.format(122.0000006)
'122.000001'

使用.precision用来确定小数点精度;其位置在倒数第二位[type]前面

>>> '{:.2f}'.format(122.0000006)
'122.00'

居中对齐,宽度20,两位小数点位置,填充为-

>>> '{:-^20.2f}'.format(122)
'-------122.00-------'

前导0和align ‘=’

对字符串指定宽度,默认alignment 为 ‘<’ 左对齐;

对数字,指定快递,默认alignmeng为‘>‘ 右对齐;

>>> '{:10}'.format('-12') #字符串
'-12       '
>>> '{:10}'.format(-12)  #数字
'       -12'

空白字符默认为空格;可以使用前导0对空白字符进行填充;

>>> '{:010}'.format(-12)
'-000000012'

使用前导0后,其对齐方式看似右对齐('>'),其实是使用了对齐方式‘=’,'='与'>'的区别在与符号位的位置

'=',符号位置在首位;即在填充位的前面

‘>’,符号位跟数字在一起

>>> '{:010}'.format(-12)
'-000000012'
>>> '{:>010}'.format(-12)
'0000000-12'
>>> '{:0=10}'.format(-12)
'-000000012'
>>> '{:0>10}'.format(-12)
'0000000-12'

format的嵌套

>>> '{:{}{}}'.format(3,.2,"f")
'3.00'

以下为官方文档的案例

>>> for align, text in zip('<^>', ['left', 'center', 'right']):
...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)
...
'left<<<<<<<<<<<<'
'^^^^^center^^^^^'
'>>>>>>>>>>>right'
>>>
>>> octets = [192, 168, 0, 1]
>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
'C0A80001'
>>> int(_, 16)
3232235521
>>>
>>> width = 5
>>> for num in range(5,12):
...     for base in 'dXob':
...         print('{0:{width}{base}}'.format(num, base=base, width=width), 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

字符串之format整理的更多相关文章

  1. Python内置的字符串处理函数整理

    Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...

  2. javascript中字符串常用操作整理

    javascript中字符串常用操作整理 字符串的操作在js中非常频繁,也非常重要.以往看完书之后都能记得非常清楚,但稍微隔一段时间不用,便会忘得差不多,记性不好是硬伤啊...今天就对字符串的一些常用 ...

  3. Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化 format函数字符串格式化 帮助

    Python第二天  变量  运算符与表达式  input()与raw_input()区别  字符编码  python转义符  字符串格式化  format函数字符串格式化  帮助 目录 Pychar ...

  4. 【转】Python格式化字符串str.format()

    原文地址:http://blog.xiayf.cn/2013/01/26/python-string-format/ 每次使用Python的格式字符串(string formatter),2.7及以上 ...

  5. 字符串str.format()方法的个人整理

    引言: 字符串的内置方法大致有40来个,但是一些常用的其实就那么20几个,而且里面还有类似的用法,区分度高比如isalpha,isalnum,isdigit,还有一些无时不刻都会用到的split切分, ...

  6. C语言字符串操作函数整理

    整理C语言字符串相关的函数,以程序方式验证,以注释方式做说明. #include<stdio.h> #include<string.h> #include<stdlib. ...

  7. Python 中格式化字符串 % 和 format 两种方法之间的区别

    Python2.6引入了 format 格式化字符串的方法,现在格式化字符串有两种方法,就是 % 和 format ,具体这两种方法有什么区别呢?请看以下解析. # 定义一个坐标值 c = (250, ...

  8. python中的printf:%号拼接字符串和format函数

    在C语言中,我们使用printf("%s","hello")这种形式进行字符串的拼接 在python中,进行这样的拼接有两种实现方式,分别是%号拼接以及使用fo ...

  9. python3字符串格式化format()函数的简单用法

    format()函数 """ 测试 format()函数 """ def testFormat(): # format()函数中有几个元素, ...

随机推荐

  1. Partition to K Equal Sum Subsets

    Given an array of integers nums and a positive integer k, find whether it's possible to divide this ...

  2. 2. zookeeper介绍及集群搭建

    ZooKeeper 概述 Zookeeper 是一个分布式协调服务的开源框架. 主要用来解决分布式集群中 应用系统的一致性问题,例如怎样避免同时操作同一数据造成脏读的问题. ZooKeeper 本质上 ...

  3. 客户A数据统计

    -------------------------------------------------- --数据准备 /*将数据调入临时表,对advalues进行计算,并将月份更新到字段int1 */ ...

  4. AssertionError [ERR_ASSERTION]: Task function must be specified,gulp版本不一致

    报错信息: vue项目打包报错 > innovate-admin-vue@ build /home/soldier/SOLDIER/IDE_project/webStorm_project/in ...

  5. (一)Java秒杀项目之项目环境搭建

    一.Spring Boot环境搭建 1.把项目分成多个模块,每个模块对应一部分(不一定是一个章节)的内容,代码将在文章的具体位置给出,每个模块都是在之前模块的基础上构建,每个模块都为Spring Bo ...

  6. [LGP5115] Check,Check,Check one two!

    神奇的思路,还是要学习一个. 题意:给你一个字符串,并定义两个前缀的lcs.两个后缀的lcp,求式子膜\(2^{64}\)的值. \[ \sum_{1\le i<j\le n} lcp(i,j) ...

  7. 第一篇 jQuery

    1-1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3. ...

  8. websocket具体如何使用

    本人是在https://blog.csdn.net/jintingbo/article/details/80755636此地址学习的,所以留做笔记用于之后的学习 现在在写一个工程,是关于监控摄像头的, ...

  9. Seeker:一款可获取高精度地理和设备信息的工具分析

    Seeker是一款可以获取高精度地理和设备信息的工具.其利用HTML5,Javascript,JQuery和PHP来抓取设备信息,以及Geolocation接口实现对设备高精度地理位置的获取. See ...

  10. 使用shell脚本自动打包上传 fir.im

    http://blog.csdn.net/wang631106979/article/details/52299083