python format 用法详解
format 用法详解
- 不需要理会数据类型的问题,在%方法中%s只能替代字符串类型
- 单个参数可以多次输出,参数顺序可以不相同
- 填充方式十分灵活,对齐方式十分强大
- 官方推荐用的方式,%方式将会在后面的版本被淘汰
format填充字符串
一 填充
1.通过位置来填充字符串
print('hello {0} i am {1}'.format('world','python'))
# 输入结果:hello world i am python
print('hello {} i am {}'.format('world','python') )
#输入结果:hello world i am python
print('hello {0} i am {1} . a now language-- {1}'.format('world','python')
# 输出结果:hello world i am python . a now language-- python
foramt会把参数按位置顺序来填充到字符串中,第一个参数是0,然后1 ……
也可以不输入数字,这样也会按顺序来填充
同一个参数可以填充多次,这个是format比%先进的地方
2.通过key来填充
obj = 'world'
name = 'python'
print('hello, {obj} ,i am {name}'.format(obj = obj,name = name))
# 输入结果:hello, world ,i am python
3.通过列表填充
list=['world','python']
print('hello {names[0]} i am {names[1]}'.format(names=list))# 输出结果:hello world i am python
print('hello {0[0]} i am {0[1]}'.format(list)) #输出结果:hello world i am python
4.通过字典填充
dict={‘obj’:’world’,’name’:’python’}
print(‘hello {names[obj]} i am {names[name]}’.format(names=dict))
# hello world i am python
注意访问字典的key,不用引号的
5.通过类的属性填充
dict={‘obj’:’world’,’name’:’python’}
print(‘hello {names[obj]} i am {names[name]}’.format(names=dict))
# hello world i am python
6.使用魔法参数
args = [‘,’,’inx’]
kwargs = {‘obj’: ‘world’, ‘name’: ‘python’}
print(‘hello {obj} {} i am {name}’.format(*args, **kwargs))
# 输入结果:hello world , i am python
注意:魔法参数跟你函数中使用的性质是一样的:这里format(*args, **kwargs)) 等价于:format(‘,’,’inx’,obj = ‘world’,name = ‘python’)
format 格式转换
数字 | 格式 | 输出 | 描述 |
---|---|---|---|
3.1415926 | {:.2f} | 3.14 | 保留小数点后两位 |
3.1415926 | {:+.2f} | 3.14 | 带符号保留小数点后两位 |
-1 | {:+.2f} | -1 | 带符号保留小数点后两位 |
2.71828 | {:.0f} | 3 | 不带小数 |
1000000 | {:,} | 1,000,000 | 以逗号分隔的数字格式 |
0.25 | {:.2%} | 25.00% | 百分比格式 |
1000000000 | {:.2e} | 1.00E+09 | 指数记法 |
25 | {0:b} | 11001 | 转换成二进制 |
25 | {0:d} | 25 | 转换成十进制 |
25 | {0:o} | 31 | 转换成八进制 |
25 | {0:x} | 19 | 转换成十六进制 |
5 | {:0>2} | 05 | 数字补零(填充左边, 宽度为2) |
5 | {:x<4} | 5xxx | 数字补x (填充右边, 宽度为4) |
10 | {:x^4} | x10x | 数字补x (填充两边,优先左边, 宽度为4) |
13 | {:10} | 13 | 右对齐 (默认, 宽度为10) |
13 | {:<10} | 13 | 左对齐 (宽度为10) |
13 | {:^10} | 13 | 中间对齐 (宽度为10) |
b、d、o、x分别是二进制、十进制、八进制、十六进制。
其它用法
1.转义“{}”
print('{{hello}} {{{0}}}'.format('world')) #输出结果:{hello} {world}
跟%中%%转义%一样,format中用 { 来转义{ ,用 } 来转义 }
2.format作为函数变量
name = 'InX'
hello = 'hello,{} welcome to python world!!!'.format #定义一个问候函数
hello(name)
# 输入结果:hello,inx welcome to python world!!!
3.格式化datetime
from datetime import datetime
now=datetime.now()
print '{:%Y-%m-%d %X}'.format(now)
# 输出结果:2017-07-24 16:51:42
4.{}内嵌{}
print('hello {0:>{1}} '.format('world',10)) ##输出结果:hello world
从最内层的{}开始格式化
5.叹号的用法
print(‘{!s}国’.format(‘中’))
# 输出结果:中国
print(‘{!a}国’.format(‘中’))
# 输出结果:’\u4e2d’国
print(‘{!s}国’.format(‘中’))
# 输出结果:’中’国
!后面可以加s r a 分别对应str() repr() ascii() 作用是在填充前先用对应的函数来处理参数
差别就是repr带有引号,str()是面向用户的,目的是可读性,repr()是面向Python解析器的,返回值表示在python内部的含义,ascii (),返回ascii编码
请给作者点赞:---> 原文链接
python format 用法详解的更多相关文章
- 关于python format()用法详解
str.format() 这个特性从python2.6而来 其实实现的效果和%有些类似 不过有些地方更方便 通过位置映射: In [1]: '{0},{1}'.format('kzc',18) Out ...
- python format用法详解
#常用方法:print('{0},{1}'.format('zhangk', 32)) print('{},{},{}'.format('zhangk','boy',32)) print('{name ...
- C#中string.format用法详解
C#中string.format用法详解 本文实例总结了C#中string.format用法.分享给大家供大家参考.具体分析如下: String.Format 方法的几种定义: String.Form ...
- C#中string.Format 用法详解
这篇文章主要介绍了C#中string.format用法,以实例形式较为详细的讲述了string.format格式化的各种用法,非常具有实用价值,需要的朋友可以参考下 本文实例总结了C#中string. ...
- python os用法详解
前言:在自动化测试中,经常需要查找操作文件,比如说查找配置文件(从而读取配置文件的信息),查找测试报告(从而发送测试报告邮件),经常要对大量文件和大量路径进行操作,这就依赖于os模块,所以今天整理下比 ...
- python yaml用法详解
YAML是一种直观的能够被电脑识别的的数据序列化格式,容易被人类阅读,并且容易和脚本语言交互.YAML类似于XML,但是语法比XML简单得多,对于转化成数组或可以hash的数据时是很简单有效的. Py ...
- C# string.format用法详解
String.Format 方法的几种定义: String.Format (String, Object) 将指定的 String 中的格式项替换为指定的 Object 实例的值的文本等效项. Str ...
- Python self用法详解
在定义类的过程中,无论是显式创建类的构造方法,还是向类中添加实例方法,都要求将 self 参数作为方法的第一个参数.例如,定义一个 Person 类: class Person: def __init ...
- Python——print用法详解
1.print语法格式 print()函数具有丰富的功能,详细语法格式如下:print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=Fa ...
随机推荐
- Corn 表达式
CronTrigger CronTriggers往往比SimpleTrigger更有用,如果您需要基于日历的概念,而非SimpleTrigger完全指定的时间间隔,复发的发射工作的时间表.CronTr ...
- CM5.7.2 yum离线安装笔记
一.建立yum本地服务源(yum支持http和ftp两种协议,这里使用http协议) 1.启动httpd服务 启动命令:service httpd start 关闭命令:service ht ...
- SyntaxHighlighter
SyntaxHighlighter uses separate syntax files called brushes to define its highlighting functionality ...
- fleet - 基于Machine Metadata的任务调度
基于Machine Metadata的任务调度 复杂和特定的要求的应用程序可以针对一个子集的集群调度通过machine metadata.强大的部署拓扑结构,可以实现的基础上的机器的地区,机架位置,磁 ...
- Fleet(集群管理器)
工作原理 fleet 是通过systemd来控制你的集群的,控制的任务被称之为unit(单元),控制的命令是fleetctl unit运行方式 unit的运行方式有两种: standard globa ...
- Kendo MVVM 数据绑定(二) Checked
Kendo MVVM 数据绑定(二) Checked Checked 绑定用在 checkbox ()或 radio button ()上.注意: checked 绑定只适用于支持 checked 的 ...
- ”position”之绝对定位深入理解
要点: 1.绝对元素脱离文档流 它从文档流中脱离了出来,后面的元素会填充掉它原来的位置 2.绝对定位元素定位 以离他最近的.有定位的.祖先元素 为准 参照对象决定元素的位置 情况1 <div ( ...
- ArrayList集合--关于System.out.print(Object obj);的理解
1.ArrayList集合中常用的方法 ArrayList<Student> stuArrayList = new ArrayList<>(); //定义一个集合对象 stuA ...
- Ubuntu获取root 权限,开机自动登入root
新机器获取root权限,只需要给root 增加密码: sudo passwd root 修改开机自动登入: #sudo gedit /etc/lightdm/lightdm.conf 修改参数: au ...
- npm在linux即mac下更新时报错
nam在linux即mac下需要更新到新版本: