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 ...
随机推荐
- T-SQL查询处理执行顺序(一)
对于T-SQL编程,用得最广泛的,莫过于查询(Querying).要想写出高质量.高性能的查询语句,必须深入地了解逻辑查询处理. 一.逻辑查询处理的各个阶段 (5)SELECT DISTINCT TO ...
- js 回车提交表单
一.整个页面用一个回车提交事件: <input type="button" value="回车提交" id="auto" onclic ...
- webpack.config.js====插件clean-webpack-plugin
1. 安装:主要是用来清除重复文件,生成最新的的插件 就是说在编译文件的时候,先把 build或dist (就是放生产环境用的文件) 目录里的文件先清除干净,再生成新的带有hash值的文件 cnpm ...
- Java中的日志框架
日志框架的介绍和使用 常见的日志框架:JUL(Java.util.logging),JCL(jakarta commons logging),SLF4J,jboss-logging,Log4j,Log ...
- css3响应式表格
<h1>极客学院相关课程</h1> <table class="responsive"> <thead> <tr> &l ...
- 集合(List、Set)
第19天 集合 第1章 List接口 我们掌握了Collection接口的使用后,再来看看Collection接口中的子类,他们都具备那些特性呢? 接下来,我们一起学习Collection中的常用几个 ...
- dubbo注解
如果还不了解Dubbo是什么或者不知道怎么搭建的可以先看一下我的上一篇文章. 首先我先来讲下提供者(也就是服务端)的配置,先上配置文件代码: <?xml version="1.0&qu ...
- 键盘各键对应的ASCII码值(包括鼠标和键盘所有的键)
ESC键 VK_ESCAPE (27)回车键: VK_RETURN (13)TAB键: VK_TAB (9)Caps Lock键: VK_CAPITAL (20)Shift键: VK_SHIFT ($ ...
- SharePoint 2013 缺少站点保存为模板选项
如果您尝试在SharePoint Server 2013中保存站点,我们没有看到“将站点另存为模板”选项,则可能是因为该站点已启用站点发布功能.如 之前文章提到 “SharePoint 2010 缺少 ...
- [web开发] Vue+Spring Boot 上海大学预约系统开发记录
前端界面 使用Quasar将组件都排好,用好css. Quasar 入门 # 确保你在全局安装了vue-cli # Node.js> = 8.9.0是必需的. $ npm install -g ...