format是是python2.6新增的一个格式化字符串的方法,相对于老版的%格式方法,它有很多优点。

1.不需要理会数据类型的问题,在%方法中%s只能替代字符串类型

2.单个参数可以多次输出,参数顺序可以不相同

3.填充方式十分灵活,对齐方式十分强大

4.官方推荐用的方式,%方式将会在后面的版本被淘汰

format的一个例子

print 'hello {0}'.format('world')

会输出hello world

format的格式

replacement_field     ::=  "{" [field_name] ["!" conversion] [":" format_spec] "}"
field_name              ::=      arg_name ("." attribute_name | "[" element_index "]")*
arg_name               ::=      [identifier | integer]
attribute_name       ::=      identifier
element_index        ::=      integer | index_string
index_string           ::=      <any source character except "]"> +
conversion              ::=      "r" | "s" | "a"
format_spec            ::=      <described in the next section>

format_spec 的格式

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

应用:

一 填充

1.通过位置来填充字符串

print 'hello {0} i am {1}'.format('Kevin','Tom')                  # hello Kevin i am Tom
print 'hello {} i am {}'.format('Kevin','Tom') # hello Kevin i am Tom
print 'hello {0} i am {1} . my name is {0}'.format('Kevin','Tom') # hello Kevin i am Tom . my name is Kevin

foramt会把参数按位置顺序来填充到字符串中,第一个参数是0,然后1 ……

也可以不输入数字,这样也会按顺序来填充

同一个参数可以填充多次,这个是format比%先进的地方

2.通过key来填充

print 'hello {name1}  i am {name2}'.format(name1='Kevin',name2='Tom')                  # hello Kevin i am Tom

3.通过下标填充

names=['Kevin','Tom']
print 'hello {names[0]} i am {names[1]}'.format(names=names) # hello Kevin i am Tom
print 'hello {0[0]} i am {0[1]}'.format(names) # hello Kevin i am Tom

4.通过字典的key

names={'name':'Kevin','name2':'Tom'}
print 'hello {names[name]} i am {names[name2]}'.format(names=names) # hello Kevin i am Tom

注意访问字典的key,不用引号的

5.通过对象的属性

class Names():
name1='Kevin'
name2='Tom' print 'hello {names.name1} i am {names.name2}'.format(names=Names) # hello Kevin i am Tom

6.使用魔法参数

args=['lu']
kwargs = {'name1': 'Kevin', 'name2': 'Tom'}
print 'hello {name1} {} i am {name2}'.format(*args, **kwargs) # hello Kevin i am Tom

二 格式转换

b、d、o、x分别是二进制、十进制、八进制、十六进制。

数字 格式 输出 描述
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)

四 其他

1.转义{和}符号

print '{{ hello {0} }}'.format('Kevin')

跟%中%%转义%一样,formate中用两个大括号来转义

2.format作为函数

f = 'hello {0} i am {1}'.format
print f('Kevin','Tom')

3.格式化datetime

now=datetime.now()
print '{:%Y-%m-%d %X}'.format(now)

4.{}内嵌{}

print 'hello {0:>{1}} '.format('Kevin',50)  

5.叹号的用法

!后面可以加s r a 分别对应str() repr() ascii()

作用是在填充前先用对应的函数来处理参数

print "{!s}".format('')  #
print "{!r}".format('') # '2'

差别就是repr带有引号,str()是面向用户的,目的是可读性,repr()是面向python解析器的,返回值表示在python内部的含义

ascii()一直报错,可能这个是3.0才有的函数

参考:https://docs.python.org/3/library/string.html#grammar-token-conversion

Python用format格式化字符串的更多相关文章

  1. .NET ToString() format格式化字符串(常用)

    前言 我们平常会用到货币数据类型,尤其当我们计算金钱或者算数的时候经常会遇到保留几位小数,而且碰到日期格式问题的时候,经常不知道选择什么样的格式比较合适,下面我找了一部分常用的.NET ToStrin ...

  2. ##C++ format 格式化字符串

    C++ format 格式化字符串实现方式 1. http://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprint ...

  3. 飘逸的python - 增强的格式化字符串format函数

    自python2.6开始,新增了一种格式化字符串的函数str.format(),可谓威力十足.那么,他跟之前的%型格式化字符串相比,有什么优越的存在呢?让我们来揭开它羞答答的面纱. 语法 它通过{}和 ...

  4. python format格式化字符串

    自python2.6开始,新增了一种格式化字符串的函数str.format() 语法 它通过{}和:来代替%. “映射”示例 通过位置 In [1]: '{0},{1}'.format('kzc',1 ...

  5. (转)飘逸的python - 增强的格式化字符串format函数

    原文:https://blog.csdn.net/handsomekang/article/details/9183303 Python字符串格式化--format()方法-----https://b ...

  6. format格式化字符串

    假如想要表达这样一条语句:李明今年十二岁 输出这样一条语句 name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') #输出 L ...

  7. Python print format() 格式化内置函数

    Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能. 基本语法是通过 {} 和 : 来代替以前的 % . format 函数可以接受不限个参数 ...

  8. python基础之格式化字符串

    一.格式化字符功能介绍 应用场景:一般在print的时候提供占位符;python中提供两种格式化字符串方式:第一种是古老的利用百分号的方式,第二种是增强的格式化字符串.format 函数. 二.古老的 ...

  9. 转载:python的format格式化输出

    https://www.cnblogs.com/chunlaipiupiupiu/p/7978669.html python中format函数   ---恢复内容开始--- python中format ...

随机推荐

  1. [Effective C++ --007]为多态基类声明virtual析构函数

    引言: 我们都知道类的一个很明显的特性是多态,比如我们声明一个水果的基类: class Fruit { public: Fruit() {}; ~Fruit(){}; } 那么我们根据这个Fruit基 ...

  2. [Effective C++ --005]了解C++默默编写并调用哪些函数

    <前言>编译器是个十分敬业的工作者,不但为你编译代码,甚至为你生成代码,不可思议吧.本文主要介绍编译器究竟会为我们生成和调用哪些代码. <空类和非空类>如果问什么样的类是空类? ...

  3. [JavaScript]转--如何让JS代码高大上

    原文出处:http://www.cnblogs.com/wenber/p/3630373.html 1,创造简短的写法 你可以这么写: 1 var slice = Array.prototype.sl ...

  4. JavaScript,Java,php的区分大小写问题

    JavaScript 对大小写敏感. JavaScript 对大小写是敏感的.JavaScript属于弱类型语言 当编写 JavaScript 语句时,请留意是否关闭大小写切换键. 函数 getEle ...

  5. C#_约束 实现可排序单链表

    using System; using System.Collections.Generic; using System.Linq; using System.Text; /* 使用 约束 实现可排序 ...

  6. 关于@see注解

    所有三种类型的注释文档都可包含@see标记,它允许我们引用其他类里的文档.对于这个标记,javadoc会生成相应的HTML,将其直接链接到其他文档.格式如下: @see 类名@see 完整类名@see ...

  7. 从lambda到函数式编程

    Object.send(:remove_const,'TRUE') Object.send(:remove_const,'FALSE') def to_integer(pro) pro[-> n ...

  8. 【转】做产品VS做项目

    相关定义 根据GB/T19000—2008<质量管理体系基础和术语>,有以下定义 过程process 一组将输入转化为输出的相互关联或相互作用的活动 注:一个过程的输入通常是其他过程的输出 ...

  9. JAXB - Annotations, The Object Factory: XmlRegistry, XmlElementDecl

    To be able to create objects from XML elements, the unmarshaller must have an object factory with me ...

  10. JAXB - Annotations, Controlling Element Selection: XmlAccessorType, XmlTransient

    If JAXB binds a class to XML, then, by default, all public members will be bound, i.e., public gette ...