字符串之format整理
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.标识符
复杂:
- 指定索引或标识符的前提下,使用其attribute_name(属性名) 比如point.x;0.name等方式
- 指定索引或标识符的前提下,使用其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整理的更多相关文章
- Python内置的字符串处理函数整理
Python内置的字符串处理函数整理 作者: 字体:[增加 减小] 类型:转载 时间:2013-01-29我要评论 Python内置的字符串处理函数整理,收集常用的Python 内置的各种字符串处理 ...
- javascript中字符串常用操作整理
javascript中字符串常用操作整理 字符串的操作在js中非常频繁,也非常重要.以往看完书之后都能记得非常清楚,但稍微隔一段时间不用,便会忘得差不多,记性不好是硬伤啊...今天就对字符串的一些常用 ...
- Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化 format函数字符串格式化 帮助
Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化 format函数字符串格式化 帮助 目录 Pychar ...
- 【转】Python格式化字符串str.format()
原文地址:http://blog.xiayf.cn/2013/01/26/python-string-format/ 每次使用Python的格式字符串(string formatter),2.7及以上 ...
- 字符串str.format()方法的个人整理
引言: 字符串的内置方法大致有40来个,但是一些常用的其实就那么20几个,而且里面还有类似的用法,区分度高比如isalpha,isalnum,isdigit,还有一些无时不刻都会用到的split切分, ...
- C语言字符串操作函数整理
整理C语言字符串相关的函数,以程序方式验证,以注释方式做说明. #include<stdio.h> #include<string.h> #include<stdlib. ...
- Python 中格式化字符串 % 和 format 两种方法之间的区别
Python2.6引入了 format 格式化字符串的方法,现在格式化字符串有两种方法,就是 % 和 format ,具体这两种方法有什么区别呢?请看以下解析. # 定义一个坐标值 c = (250, ...
- python中的printf:%号拼接字符串和format函数
在C语言中,我们使用printf("%s","hello")这种形式进行字符串的拼接 在python中,进行这样的拼接有两种实现方式,分别是%号拼接以及使用fo ...
- python3字符串格式化format()函数的简单用法
format()函数 """ 测试 format()函数 """ def testFormat(): # format()函数中有几个元素, ...
随机推荐
- 【案例分享】在 React 框架中使用 SpreadJS 纯前端表格控件
[案例分享]在 React 框架中使用 SpreadJS 纯前端表格控件 本期葡萄城公开课,将由国电联合动力技术有限公司,资深前端开发工程师——李林慧女士,与大家在线分享“在 React 框架中使用 ...
- Microsoft SQL server 2012数据库学习总结(一)
一.Microsoft SQL Server2012简介 1.基本概要 Microsoft SQL Server 2012是微软发布的新一代数据平台产品,全面支持云技术与平台,并且能够快速构建相应的解 ...
- Python学习【day04】- Python基础(集合、函数)
集合 #!/usr/bin/env python # -*- coding:utf8 -*- # set集合 只可放不可变的数据类型,本身是可变数据类型,无序 # s = {1,2,3,[1,2,3] ...
- Maven引入oracle驱动包
1.下载驱动包 2.加载到本地maven库中 mvn install:install-file -DgroupId=com.oracle -DartifactId=ojdbc6 -Dversion=1 ...
- 使用Python基于HyperLPR/Mask-RCNN的中文车牌识别
基于HyperLPR的中文车牌识别 Bolg:https://blog.csdn.net/lsy17096535/article/details/78648170 https://www.jiansh ...
- 外贸开发,用java调用速卖通api第一步,token的获取。
第一步 定义速卖通api的常量 public String client_id; public String client_key; public String site; 第二步 获取登 ...
- Binding的Path(路径)
Binding的源可以是控件(一个控件是另一个控件的Source.控件把自己的容器作为Source),把集合作为ItemsControls的Source,把xml作为Tree或者Menu的Source ...
- [转载]for、foreach、iterator的用法及效率区别
来源:https://www.jianshu.com/p/bbb220824c9a 1.在形式上 for的形式是 for(int i=0;i<arr.size();i++){...} forea ...
- mybatis-plus简单了解
mybatis-plus入门了解和简单使用 MyBatis-Plus(简称 MP)是一个 MyBatis 的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发.提高效率而生. 特性: ...
- 15 Python之内置函数
思维导图: https://www.processon.com/mindmap/5c10cb5ee4b0090a2c9db92f 1. 匿名函数统一的名字是:<lambda> 使用场景: ...