笔记-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. 洛谷P3603 || bzoj 4763 雪辉 && bzoj4812: [Ynoi2017]由乃打扑克

    https://www.luogu.org/problemnew/show/P3603 https://www.lydsy.com/JudgeOnline/problem.php?id=4763 就是 ...

  2. Crusher Django 学习笔记2 基本url配置

    http://crusher-milling.blogspot.com/2013/09/crusher-django-tutorial2-conf-basic-url.html 顺便学习一下FQ Cr ...

  3. mysql设置自增长列的当前值

    -- 查看表中自增长列的当前值 SELECT Auto_increment FROM information_schema.`TABLES` WHERE Table_Schema='rhr' AND ...

  4. 单线程异步回调机制的缺陷与node的解决方案

    一.node单线程异步的缺陷: 单线程异步的优点自然不必多说,node之所以能够如此快的兴起,其单线程异步回调机制相比于传统同步执行编程语言的优势便是原因之一.然而,开发一个node程序,其缺陷也是不 ...

  5. git与GitHub(二)

    昨天在安装完git之后,出了一个问题,虽然暂时有解决的办法,但是由于电脑中了病毒并且配置低下等原因,这个问题的解决办法目前还有待考证.遇到的问题是这样的: 前提是想试一下git在命令行里的命令:于是: ...

  6. 解决spring http输入流和输出流只能读取一次

    1.需求:给某些请求接口记录日志,记录请求的数据和响应的数据和请求所花费的时间.这里采用非侵入式编程,也业务代码进行解耦.按照spring AOP 的编程思想. 2.编程设计:在spring 拦截器中 ...

  7. 【进度总结】第一个web应用程序(未完成)

    web程序快速导航 使用Eclipse for Java EE Web Development,并配置Tomcat,这部分内容在众多教程中都描述的十分详细.我直接从代码部分开始记录流程: 这张图是We ...

  8. 【R语言进行数据挖掘】回归分析

    1.线性回归 线性回归就是使用下面的预测函数预测未来观测量: 其中,x1,x2,...,xk都是预测变量(影响预测的因素),y是需要预测的目标变量(被预测变量). 线性回归模型的数据来源于澳大利亚的C ...

  9. Selenium私房菜系列6 -- 深入了解Selenium RC工作原理(1)

    前一篇已经比较详细讲述了如何使用Selenium RC进行Web测试,但到底Selenium RC是什么?或者它由哪几部分组成呢?? 一.Selenium RC的组成: 关于这个问题,我拿了官网上的一 ...

  10. sysbench0.5安装介绍

    sysbench是一个模块化的.跨平台.多线程基准测试工具,主要用于评估测试各种不同系统参数下的数据库负载情况,sysbench支持MySQL.PostgreSQL.Oracle数据库OLTP测试.它 ...