字符串之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()函数中有几个元素, ...
随机推荐
- Oacle常用语句
1.建表语句 ) NOT NULL, region_id ) NOT NULL, salesperson_id ) NOT NULL, ) NOT NULL, ) NOT NULL, tot_orde ...
- 什么是云数据库POLARDB
POLARDB是阿里巴巴自主研发的下一代关系型分布式云原生数据库,目前兼容三种数据库引擎:MySQL.Oracle.PostgreSQL.计算能力最高可扩展至1000核以上,存储容量最高可达 100T ...
- java-selenium上传
一.sendkeys()上传 HTML源码 <td>sendkeys上传</td> <div id='pf'><input type='file' id='p ...
- C++练习 | 单链表的创建与输出(结构体格式)
#include <iostream> #include <stdio.h> using namespace std; #define OK 1 #define ERROR 0 ...
- python 操作mongodb 文件相关
https://api.mongodb.com/python/current/tutorial.html# 文档地址 from pymongo import MongoClientfrom gridf ...
- VUE(下)
VUE(下) VUE指令 表单指令 数据的双向指令 v-model = "变量" model绑定的变量,控制的是表单元素的value值 普通表单元素用v-model直接绑定控制va ...
- CentOS 7 yum安装LAMP,LNMP并搭建WordPress个人博客网站
本次实验要进行的是在CentOS7.2,内核版本3.10.0-327.el7.x86_64的环境下搭建LAMP和LNMP,并在此之上做一个WordPress博客网站. [root@Shining ~] ...
- CPU如何区分溢出和自然进位?
CPU如何区分溢出和自然进位? 之前学习补码的时候倒是学会了基本概念,但是最近又接触时发现还有不清楚的地方,所以又研究了下 今天的核心问题的"CPU是如何区分高位自然舍弃和溢出的?" ...
- 爬取YY评级信息
#!/usr/bin/env python # -*- coding: utf-8 -*- # @File : 爬取YY评级基本信息.py # @Author: lattesea # @Date : ...
- GitLab: Deploy keys are not allowed to push code.
被这个问题坑了,大半天.写此博文,愿入坑的童鞋能及时托坑 一.当你第一次pull或者push gitlab远程项目的时候提示你一个该建立一个sshkey,此时你在客户端生成sshkey 二.切记要把这 ...