1、python到底有那几种字符串格式化模块?

python有3种格式化字符串的方法:

  • 传统的%字符串格式符
  • str.format函数
  • 字符串模版template

新的python 3.6+还提供了新的f修饰符

2、传统的%字符串格式符

python采用了类似于在C语言中使用sprintf的字符串格式化输出。String对象有一个独特的内置操作:%操作符。 这也称为字符串格式化或插值运算符。 给定格式%值(其中format是字符串),转换规范将格式的%将替换为零个或多个元素值。

‘%[[(key)][flag][width][.precision]]type’%(key list)

如果format单个参数,则key可以是单个非元组对象: ‘%s’%key。否则,值必须是具有格式字符串指定的项目数的元组,或者是单个映射对象(例如,字典)。

flag可以是#, 0, -, 空格,或是+:

Flag    意义
# The value conversion will use the ``alternate form'' (where defined below).
The conversion will be zero padded for numeric values.
- The converted value is left adjusted (overrides the "" conversion if both are given).
(a space) A blank should be left before a positive number (or empty string) produced by a signed conversion.
+ A sign character ("+" or "-") will precede the conversion (overrides a "space" flag).

type可以是下面定义不同类型:

type 意义                    注释
d Signed integer            decimal.
i Signed integer            decimal.
o Unsigned octal.           ()
u Unsigned                decimal.
x Unsigned hexadecimal (lowercase). ()
X Unsigned hexadecimal (uppercase). ()
e Floating point exponential format (lowercase).
E Floating point exponential format (uppercase).
f Floating point             decimal format.
F Floating point             decimal format.
g Same as "e" if exponent is greater than - or less than precision, "f" otherwise.
G Same as "E" if exponent is greater than - or less than precision, "F" otherwise.
c Single character (accepts integer or single character string).
r String (converts any python object using repr()). ()
s String (converts any python object using str()). ()
% No argument is converted, results in a "%" character in the result.

比如:

  • >>> '%(name)s GPA is %(#)07.3f'%{'name':'Yue', '#':88.2}
    'Yue GPA is 088.200'

  • >>> '%(name)10s GPA is %(#) 7.2f'%{'name':'Jun', '#':89.1299}
    '          Jun GPA is 89.13'

3. str.format函数

PEP 3101 规定了使用str.format()函数格式化字符串的标准。str.format()的语法:

'...{replacement_field}...'.format(*arg, **kargs)

具体解释如下:

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"
format_spec ::= <described in the next section>

例子:

>>> 'Bring {0} a {1}'.format('me', 'apple')  # 和C#有点像,数字代表位置
'Bring me a apple'
>>> 'Bring {} a {}'.format('me', 'apple')
'Bring me a apple'
>>> 'Bring {name} a {fruit}'.format(fruit='me', name='apple')
'Bring apple a me'

下面是format_spec的定义:

format_spec ::=  [[fill]align][sign][#][][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" | "%"

有时候,还需要更进一步定制,这时需要使用string模块里的formatter类来定制格式, Formatter类有以下公共函数:

  • format(format_string*args**kwargs):它调用下面vformat函数。
  • vformat(format_stringargskwargs):根据参数和格式化串产生相应的字符串。它调用下面可以重载的函数。

此外,Formatter类还定义了其他一些可以重载的函数:

  • parse(format_string):分解格式化定义format_string;
  • get_field(field_nameargskwargs):根据parse()的输出,为某一field产生格式化对象;
  • get_value(keyargskwargs):获取某一field的值;
  • check_unused_args(used_argsargskwargs)
  • format_field(valueformat_spec)
  • convert_field(valueconversion)

4. 字符串模版template

模板支持基于$的替换,而不是正常的基于%的替换:

  • $$用于替换$。
  • $ identifier命名匹配映射关键字“identifier”的替换占位符。 默认情况下,“identifier”必须拼写Python标识符。 $字符后面的第一个非标识符字符终止此占位符规范。
  • $ {identifier}相当于$ identifier。 当有效标识符字符跟随占位符但不是占位符的一部分时,例如“$ {noun} ification”,则需要它。
  • 字符串中$在其他任何地方出现,都将导致ValueError异常。

例子:

>>> from string import Template
>>> s1 = Template('Today is $weekday, it is $weather')
>>> s1.substitute(weekday = 'Tuesday', weather = 'sunny')
'Today is Tuesday, it is sunny'
>>> s1.substitute(weekday = 'Tuesday')
...
KeyError: 'weather'
>>> s1.safe_substitute(weekday = 'Tuesday')
'Today is Tuesday, it is $weather'
>>> s2 = Template('$fruit is $2.99 per pound')
>>> s2.substitute(fruit = 'apple')
...
ValueError: Invalid placeholder in string: line , col
>>> s2 = Template('$fruit is $$2.99 per pound')
>>> s2.substitute(fruit = 'apple')
'apple is $2.99 per pound'

References:

[1] https://docs.python.org/2/library/stdtypes.html#string-formatting

[2] https://docs.python.org/2/library/string.html

python的字符串格式化的更多相关文章

  1. Python基础-字符串格式化_百分号方式_format方式

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

  2. python(七)字符串格式化、生成器与迭代器

    字符串格式化 Python的字符串格式化有两种方式:百分号方式.format方式 1.百分号的方式 %[(name)][flags][width].[precision]typecode (name) ...

  3. Python 的字符串格式化和颜色控制

    (部分内容源自武神博客和网络收集.) Python的字符串格式化有两种方式: 百分号方式.format方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两 ...

  4. Python:字符串格式化

    Python中提供了多种格式化字符串的方式,遇到一个项目,在一个文件中,就用了至少两种方式.特别是在使用Log时,更让人迷惑. 因此特地花时间来了解一下Python中字符串格式化的几种方式: # -* ...

  5. python中字符串格式化%与.format

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

  6. Python进阶-字符串格式化

    目录 前言 %格式化 str.format() f-Strings 特殊符号处理 前言 在 Python 3.6 之前,字符串格式化方法主要有两种: %格式化 str.format() 在Python ...

  7. Python: 字符串格式化format()函数的使用

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

  8. 第十篇 Python的字符串格式化

    字符串格式化:就是按照你的意愿做一个拼接的过程. 1. 字符串格式化的第一种方式:百分号方式 百分号的方式相对来说比较老,而format方式则是比较先进的方式,企图替换古老的方式,目前两者并存. %[ ...

  9. python中字符串格式化的意义(化妆)

    格式 描述%% 百分号标记 #就是输出一个%%c 字符及其ASCII码%s 字符串%d 有符号整数(十进制)%u 无符号整数(十进制)%o 无符号整数(八进制)%x 无符号整数(十六进制)%X 无符号 ...

随机推荐

  1. SAP NetWeaver BPM

    什么是BPM? BPM是Business Process Management的缩写,翻译过来是业务流程管理.BPM本身并没有明确的定义,它更多的是一种概念,这个概念本身的产生来源于企业对众多业务系统 ...

  2. 约束,索引,rownum&rownum

    --constraint --not null 非空约束 --unique 唯一键 --非空&唯一 --自定义检查约束 --创建约束时,为约束起名 --在添加完列后,还可以添加约束 --除了n ...

  3. [luogu1081] 开车旅行

    题面 ​ 这个题目还是值得思考的. ​ 看到这个题目, 大家应该都想到了这样一个思路, 就是把每个点能够达到的最近的和次近的点都预处理出来, 然后跑就可以了, 现在问题就是难在这个预处理上面, 我们应 ...

  4. SVN 客户端使用

    一.TortoiseSVN基本设置 1.1 客户端设置     1.1  语言设置       二.基本操作 2.1 浏览服务器           用户名跟密码,跟公司配置管理员人员获取,没有专门的 ...

  5. C#做一个简单的进行串口通信的上位机

    C#做一个简单的进行串口通信的上位机   1.上位机与下位机 上位机相当于一个软件系统,可以用于接收数据.控制数据.即可以对接收到的数据直接发送操控命令来操作数据.上位机可以接收下位机的信号.下位机是 ...

  6. SICP 习题 (1.35)解题总结

    SICP 习题 1.35要求我们证明黄金切割率φ 是变换函数 x => 1+ 1/x 的不动点,然后利用这一事实通过过程fixed-point 计算出φ的值. 首先是有关函数的不动点,这个概念须 ...

  7. 三层架构搭建(asp.net mvc + ef)

    第一次写博客,想了半天先从简单的三层架构开始吧,希望能帮助到你! 简单介绍一下三层架构, 三层架构从上到下分:表现层(UI),业务逻辑层(BLL),数据访问层(DAL)再加上数据模型(Model),用 ...

  8. MySQL-ALTER TABLE命令学习[20180503]

    学习ALTER TABLE删除.添加和修改字段和类型     CREATE TABLE alter_tab01(     id int,     col01 char(20))     engin=I ...

  9. jQuery----五星好评实现

    在美团.淘宝.京东等网页上,有许多商品.服务评价页面,五星好评功能很常见,本文利用jQuery实现五星好评功能. 案例图片:                                       ...

  10. vue实现两重列表集合,点击显示,点击隐藏的折叠效果,(默认显示集合最新一条数据,点击展开,显示集合所有数据)

    效果图: 默认显示最新一条数据: 点击显示所有数据: 代码: 说明:这里主要是 这块用来控制显示或者隐藏 根据当前点击的  这个方法里传递的index 对应  isShow 数组里的index  ,对 ...