原文:https://www.cnblogs.com/wilber2013/p/4641616.html

http://blog.konghy.cn/2016/11/25/python-str-format/

Python 在 2.6 版本中新加了一个字符串格式化方法: str.format()。它的基本语法是通过 {} 和 :来代替以前的 %.。格式化时的占位符语法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”规则

通过位置

str.format() 可以接受不限个参数,位置可以不按顺序:

>>> "{0} {1}".format("hello", "world")
'hello world'
>>> "{} {}".format("hello", "world")
'hello world'
>>> "{1} {0} {1}".format("hello", "world")
'world hello world'

通过关键字参数

使用关键参数时字符串中需要提供参数名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)
'I am huoty, age is 18'
>>> user = {"name": "huoty", "age": 18}
>>> "I am {name}, age is {age}".format(**user)
'I am huoty, age is 18'

通过对象属性

str.format() 可以直接读取用户属性:

>>> class User(object):
... def __init__(self, name, age):
... self.name = name
... self.age = age
...
... def __str__(self):
... return "{self.name}({self.age})".format(self=self)
...
... def __repr__(self):
... return self.__str__()
...
...
>>> user = User("huoty", 18)
>>> user
huoty(18)
>>> "I am {user.name}, age is {user.age}".format(user=user)
'I am huoty, age is 18'

通过下标

在需要格式化的字符串内部可以通过下标来访问元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]
>>> "I am {0[0]}, age is {1[2]}".format(names, ages)
'I am huoty, age is 8'
>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}
>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定转化

可以指定字符串的转化类型:

 conversion ::= "r" | "s" | "a"

其中 "!r" 对应 repr(); "!s" 对应 str(); "!a" 对应 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')
"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充与对齐

填充常跟对齐一起使用。^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

>>> "{:>8}".format("181716")
' 181716'
>>> "{:0>8}".format("181716")
'00181716'
>>> "{:->8}".format("181716")
'--181716'
>>> "{:-<8}".format("181716")
'181716--'
>>> "{:-^8}".format("181716")
'-181716-'
>>> "{:-<25}>".format("Here ")
'Here -------------------->'

浮点精度

用 f 表示浮点类型,并可以在其前边加上精度控制:

>>> "[ {:.2f} ]".format(321.33345)
'[ 321.33 ]'
>>> "[ {:.1f} ]".format(321.33345)
'[ 321.3 ]'
>>> "[ {:.4f} ]".format(321.33345)
'[ 321.3335 ]'
>>> "[ {:.4f} ]".format(321)
'[ 321.0000 ]'

还可以为浮点数指定符号,+ 表示在正数前显示 +,负数前显示 -; (空格)表示在正数前加空格,在幅负数前加 -;- 与什么都不加({:f})时一致:

>>> '{:+f}; {:+f}'.format(3.141592657, -3.141592657)
'+3.141593; -3.141593'
>>> '{: f}; {: f}'.format(3.141592657, -3.141592657)
' 3.141593; -3.141593'
>>> '{:f}; {:f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:-f}; {:-f}'.format(3.141592657, -3.141592657)
'3.141593; -3.141593'
>>> '{:+.4f}; {:+.4f}'.format(3.141592657, -3.141592657)
'+3.1416; -3.1416'

截取字符串

截取字符串类似于浮点精度控制,只是不需要加 f 在指定是浮点数:

>>> '{:.2}'.format("hello")
'he'
>>> '{:.3}'.format("huayong")
'hua'

指定进制

>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(18)
'int: 18; hex: 12; oct: 22; bin: 10010'
>>> "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(18)
'int: 18; hex: 0x12; oct: 0o22; bin: 0b10010'

千位分隔符

可以使用 "," 来作为千位分隔符:

>>> '{:,}'.format(1234567890)
'1,234,567,890'

百分数显示

>>> "progress: {:.2%}".format(19.88/22)
'progress: 90.36%'

事实上,format 还支持更多的类型符号:

type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"

其他技巧

占位符嵌套

某些时候占位符嵌套还是很有用的:

>>> '{0:{fill}{align}16}'.format("hello", fill='*', align='^')
'*****hello******'
>>>
>>> for num in range(5,12):
... for base in "dXob":
... print("{0:{width}{base}}".format(num, base=base, width=5), 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

作为函数使用

可以先不指定格式化参数,而是在不要的地方作为函数来调用:

>>> email_f = "Your email address was {email}".format
>>> print(email_f(email="suodhuoty@gmail.com"))
Your email address was sudohuoty@gmail.com

转义大括号

当在字符串中需要使用大括号时可以用大括号转义:

>>> " The {} set is often represented as { {0} } ".format("empty")
' The empty set is often represented as {0} '

(转)Python 字符串格式化 str.format 简介的更多相关文章

  1. python字符串格式化方法 format函数的使用

      python从2.6开始支持format,新的更加容易读懂的字符串格式化方法, 从原来的% 模式变成新的可读性更强的 花括号声明{}.用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序 ...

  2. python字符串格式化之format

    用法: 它通过{}和:来代替传统%方式 1.使用位置参数 要点:从以下例子可以看出位置参数不受顺序约束,且可以为{},只要format里有相对应的参数值即可,参数索引从0开,传入位置参数列表可用*列表 ...

  3. python 字符串格式化 ( 百分号 & format )

    Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. ----百分号 tpl = ...

  4. 字符串格式化str.format

    一.字符串格式化之str.format 1.位置参数:用{0},{1},{2}表示位置 v1 = '{1},{0},{1}'.format('a','b') #输出b,a,b 2.关键词参数:用{na ...

  5. 一文秒懂!Python字符串格式化之format方法详解

    format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符串,一定程度上与%目的一致.但在某些方面更加的方便 1.基本用法 1.按照{}的顺序依次匹配括号中的值 s = &q ...

  6. 【Python】更优的字符串格式化方式 -- "format"替代"%s"

    背景 前段时间看了一篇介绍Python的代码技巧的文章,建议格式化字符串时使用"format"代替使用"%",但是没有说明原因.各博客网站介绍相关用法的博客很多 ...

  7. python字符串格式化 %操作符 {}操作符---总结

    Python字符串格式化 (%占位操作符) 在许多编程语言中都包含有格式化字符串的功能,比如C和Fortran语言中的格式化输入输出.Python中内置有对字符串进行格式化的操作 %. 模板 格式化字 ...

  8. 【转】Python字符串格式化

    Python 支持格式化字符串的输出 .尽管这样可能会用到非常复杂的表达式,但最基本的用法是将一个值插入到一个有字符串格式符 %s 的字符串中. 在 Python 中,字符串格式化使用与 C 中 sp ...

  9. 7. python 字符串格式化方法(2)

    7. python 字符串格式化方法(2) 紧接着上一章节,这一章节我们聊聊怎样添加具体格式化 就是指定替换字段的大小.对齐方式和特定的类型编码,结构如下: {fieldname!conversion ...

随机推荐

  1. UVaLive 4043 Ants (最佳完美匹配)

    题意:给定 n 个只蚂蚁和 n 棵树的坐标,问怎么匹配使得每个蚂蚁到树的连线不相交. 析:可以把蚂蚁和树分别看成是两类,那么就是一个完全匹配就好,但是要他们的连线不相交,那么就得考虑,最佳完美匹配是可 ...

  2. rinetd小记

    官网:http://www.boutell.com/rinetd/ 下载地址:http://www.boutell.com/rinetd/http/rinetd.tar.gz 编译安装: 对于Wind ...

  3. Thread.sleep() 和 Thread.yield() 区别

    1. Thread.yield(): api中解释: 暂停当前正在执行的线程对象,并执行其他线程. 注意:这里的其他也包含当前线程,所以会出现以下结果. public class Test exten ...

  4. How to Baskup and Restore a MySQL database

    If you're storing anything in MySQL databases that you do not want to lose, it is very important to ...

  5. IPv4&&IPv6地址结构分析

    IPv4套接字地址结构: 套接字都需要有一个指向套接字地址结构的指针作为参数.每个协议簇都定义它自己的套接字地址结构.这些结构的名字均已sockaddr_开头,并以对应每个协议族的唯一后缀结尾. wi ...

  6. Flink本地环境安装部署

    本次主要介绍flink1.5.1版本的本地环境安装部署,该版本要求jdk版本1.8以上. 下载flink安装包:http://archive.apache.org/dist/flink/flink-1 ...

  7. Java Web系列:JDBC 基础

    ADO.NET在Java中的对应技术是JDBC,企业库DataAccessApplicationBlock模块在Java中的对应是spring-jdbc模块,EntityFramework在Java中 ...

  8. IDEA配置hibernate

    当做完struts2的demo之后,发现这些和myeclipse下面几乎没有差别. 唯一觉得不好的就有一点,model的映射文件 .hbm.xml这个无法通过model来生成,所以是手写,有点麻烦.这 ...

  9. yum反查某个命令或so库在哪个包里面

    yum whatprovides "*/XXX.so.1"

  10. 修改chrome插件

    背景 例子为:ModHeader插件,顾名思义可以修改request header的插件,官方地址为:https://chrome.google.com/webstore/detail/modhead ...