笔记-python-字符串格式化-format()

1.      简介

本文介绍了python 字符串格式化方法format()的常规使用方式。

2.      使用

2.1.    Accessing arguments by position:

>>> '{0}, {1}, {2}'.format('a', 'b', 'c')

'a, b, c'

>>> '{}, {}, {}'.format('a', 'b', 'c')  # 3.1+ only

'a, b, c'

>>> '{2}, {1}, {0}'.format('a', 'b', 'c')

'c, b, a'

>>> '{2}, {1}, {0}'.format(*'abc')      # unpacking argument sequence

'c, b, a'

>>> '{0}{1}{0}'.format('abra', 'cad')   # arguments' indices can be repeated

'abracadabra'

2.2.    Accessing arguments by name:

>>> 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')

'Coordinates: 37.24N, -115.81W'

>>> coord = {'latitude': '37.24N', 'longitude': '-115.81W'}

>>> 'Coordinates: {latitude}, {longitude}'.format(**coord)

'Coordinates: 37.24N, -115.81W'

2.3.    Accessing arguments’ attributes:

>>> c = 3-5j

>>> ('The complex number {0} is formed from the real part {0.real} '

...  'and the imaginary part {0.imag}.').format(c)

'The complex number (3-5j) is formed from the real part 3.0 and the imaginary part -5.0.'

>>> class Point:

...     def __init__(self, x, y):

...         self.x, self.y = x, y

...     def __str__(self):

...         return 'Point({self.x}, {self.y})'.format(self=self)

...

>>> str(Point(4, 2))

'Point(4, 2)'

2.4.    Accessing arguments’ items:

>>> coord = (3, 5)

>>> 'X: {0[0]};  Y: {0[1]}'.format(coord)

'X: 3;  Y: 5'

Replacing %s and %r:

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

"repr() shows quotes: 'test1'; str() doesn't: test2"

2.5.    Aligning the text and specifying a width:

>>> '{:<30}'.format('left aligned')

'left aligned                  '

>>> '{:>30}'.format('right aligned')

'                 right aligned'

>>> '{:^30}'.format('centered')

'           centered           '

>>> '{:*^30}'.format('centered')  # use '*' as a fill char

'***********centered***********'

Replacing %+f, %-f, and % f and specifying a sign:

>>>

>>> '{:+f}; {:+f}'.format(3.14, -3.14)  # show it always

'+3.140000; -3.140000'

>>> '{: f}; {: f}'.format(3.14, -3.14)  # show a space for positive numbers

' 3.140000; -3.140000'

>>> '{:-f}; {:-f}'.format(3.14, -3.14)  # show only the minus -- same as '{:f}; {:f}'

'3.140000; -3.140000'

Replacing %x and %o and converting the value to different bases:

>>>

>>> # format also supports binary numbers

>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)

'int: 42;  hex: 2a;  oct: 52;  bin: 101010'

>>> # with 0x, 0o, or 0b as prefix:

>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)

'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

2.6.    Using the comma as a thousands separator:

>>> '{:,}'.format(1234567890)

'1,234,567,890'

2.7.    Expressing a percentage:

>>> points = 19

>>> total = 22

>>> 'Correct answers: {:.2%}'.format(points/total)

'Correct answers: 86.36%'

2.8.    Using type-specific formatting:

>>> import datetime

>>> d = datetime.datetime(2010, 7, 4, 12, 15, 58)

>>> '{:%Y-%m-%d %H:%M:%S}'.format(d)

'2010-07-04 12:15:58'

2.9.    Nesting arguments and more complex examples:

>>> for align, text in zip('<^>', ['left', 'center', 'right']):

...     '{0:{fill}{align}16}'.format(text, fill=align, align=align)

...

'left<<<<<<<<<<<<'

'^^^^^center^^^^^'

'>>>>>>>>>>>right'

>>>

>>> octets = [192, 168, 0, 1]

>>> '{:02X}{:02X}{:02X}{:02X}'.format(*octets)

'C0A80001'

>>> int(_, 16)

3232235521

>>>

>>> width = 5

>>> for num in range(5,12):

...     for base in 'dXob':

...         print('{0:{width}{base}}'.format(num, base=base, width=width), 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

笔记-python-字符串格式化-format()的更多相关文章

  1. python 字符串格式化—format

    Python2.6 开始,新增了一种格式化字符串的函数 str.format().使用起来简单方便,不会遇到使用%时候格式的选择问题. 按照参数默认顺序 >>> "yesd ...

  2. python 字符串格式化format

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

  3. python 字符串格式化 format

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

  4. Python字符串格式化--format()方法

    https://blog.csdn.net/i_chaoren/article/details/77922939       csdn

  5. Python第二天 变量 运算符与表达式 input()与raw_input()区别 字符编码 python转义符 字符串格式化 format函数字符串格式化 帮助

    Python第二天  变量  运算符与表达式  input()与raw_input()区别  字符编码  python转义符  字符串格式化  format函数字符串格式化  帮助 目录 Pychar ...

  6. Python 字符串格式化

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

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

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

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

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

  9. Python中格式化format()方法详解

    Python中格式化format()方法详解 Python中格式化输出字符串使用format()函数, 字符串即类, 可以使用方法; Python是完全面向对象的语言, 任何东西都是对象; 字符串的参 ...

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

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

随机推荐

  1. 安装gnvm (windows下nodejs版本管理工具)

    一些写在前面的话,为什么装这个?前两天看avalon视频的时候,里面有介绍去哪儿的前端构建工具fekit.我这人吧,好奇心特别强,就打算安装用用看.在安装时它提示要求node版本0.8.x,所以我选择 ...

  2. Unity Shader入门精要学习笔记 - 第13章 使用深度和法线纹理

    线纹理的代码非常简单,但是我们有必要在这之前首先了解它们背后的实现原理. 深度纹理实际上就是一张渲染纹理,只不过它里面存储的像素值不是颜色值而是一个高精度的深度值.由于被存储在一张纹理中,深度纹理里的 ...

  3. 表单辅助函数-form_open()

    使用from_open()之前需要装载本辅助函数: $this->load->helper('form'); php===> echo form_open('email/send') ...

  4. ueditor单独调用图片上传

    很多人在问ueditor,如何单独使用图片上传功能,但是网上没有一篇能用的文档,没办法,我刚好也需要这个功能,花了3天时间(本人水平太菜,哎)终于知道怎么处理了,发出来给大家共享: 效果如下: 页面效 ...

  5. MFC 消息中( WPARAM wParam,LPARAM lParam)包含信息

    windows的消息具有以下两个参数: (1)字参数(wParam) (2)长参数(lParam) 字参数和长参数都是32位整数,用于提供消息的附带消息,是消息传递过程中参数的载体.附加信息的消息号取 ...

  6. (转)ASIC设计中各个阶段需要注意的问题——节选

    ASIC 的复杂性不断提高,同时工艺在不断地改进,如何在较短的时间内开发一个稳定的可重用的ASIC芯片的设计,并且一次性流片成功,这需要一个成熟的ASIC 的设计方法和开发流程.本文结合NCveril ...

  7. 学习用5W1H来管理自己的项目/工作

    学习用5W1H来管理自己的项目/工作   最近开始需要系统化的思维模型,这只是一个开始,一下用脑图的形式来简介5W1H的具体内容: 先写xmind思维树的文本导出,后面附上图片.^ _ ^ 5W1H ...

  8. windows下Mongodb和Memcached安装笔记

    MongoDB安装: D:\ProgramFiles\MongoDBServer3.2\bin\mongod --dbpath D:\mongoData D:\ProgramFiles\MongoDB ...

  9. js生成txt文件

    HTML CODE: <div class="modal-footer"> <a onfocus="this.blur();" id=&quo ...

  10. (五)maven之外置maven

    eclipse外置maven eclipse内置的maven插件是固定版本,如果要用其他版本的maven,可以使用外置maven. ①    在菜单栏上点击“Windows”à“Preferences ...