笔记-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

python0b1010_笔记-python-字符串格式化-format()相关推荐

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

    1.简单运用 字符串类型格式化采用format()方法,基本使用格式是:      <模板字符串>.format(<逗号分隔的参数>) 调用format()方法后会返回一个新的 ...

  2. python字符串format方法参数解释,一文秒懂!Python字符串格式化之format方法详解

    一文秒懂!Python字符串格式化之format方法详解 一文秒懂!Python字符串格式化之format方法详解 format是字符串内嵌的一个方法,用于格式化字符串.以大括号{}来标明被替换的字符 ...

  3. Python字符串格式化,%和format函数

    Python字符串格式化 格式化的操作有两种 一.使用%,常用的格式化 格式 描述 %s 字符串 %d 有符号整数(十进制) %f 浮点数 %O 转换为带符号的八进制形式的整数 %X 转换为带符号的十 ...

  4. 这篇文章有点长,但绝对是保姆级的Python字符串格式化讲解

    相关文件 想学Python的小伙伴可以关注小编的公众号[Python日志] 有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!! Python学习交流群:773162165 前言 今 ...

  5. python使用字典格式化字符串-Python字符串格式化-学这些就够用了

    一.思考❓❔ 1.什么是字符串格式化? 将变量(对象)的值填充到字符串中 在字符串中解析Python表达式 对字符串进行格式化显示 左对齐.右对齐.居中对齐 保留数字有效位数 2.你学过的字符串格式化 ...

  6. python3 format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  7. format函数_Python学习教程:Python3之字符串格式化format函数详解(上)

    Python学习教程:Python3之字符串格式化format函数详解(上) 概述 在Python3中,字符串格式化操作通过format()方法或者f'string'实现.而相比于老版的字符串格式化方 ...

  8. 字符串格式化-format()

    字符串格式化-format() 转载请标明出处(http://blog.csdn.net/lis_12/article/details/52712994). 普通格式化方法 (%s%d)生成格式化的字 ...

  9. python字符串格式化深入详解(四种方法)

    前言:本文详细整理了python字符串格式化的几种方式. 一.使用 % 符号来进行格式化 格式符为真实值预留位置,并控制显示的格式.格式符可以包含有一个类型码,用以控制显示的类型,如下: %s    ...

  10. 深度梳理:史上最全 Python 字符串格式化讲解

    大家好,今天给大家分享一篇堪称史上最全对字符串格式化的文章.喜欢点赞.收藏.关注. 上个周末看到"pandas数据格式化处理"的时候,想着把(设置小数位数,设置百分位,设置千位分隔 ...

最新文章

  1. 机器学习算法面试—口述(4):决策树
  2. 二次元妹子五官画风都能改,周博磊团队用无监督方法控制GAN | CVPR 2021
  3. IBM Java多线程 - 3.无处不在的线程
  4. Python 技术篇 - 通过代码查看文本的编码类型实例演示,如何查看文件的编码类型,文件编码查看方法
  5. pom.xml配置文件中所有标签及作用简单描述
  6. JS实现滚动监听以及滑动到顶部
  7. flask 启动服务
  8. 性能测试之JMeter函数助手详解
  9. SQL Server游标使用快速上手
  10. python写作_开源一个Python文档写作应用:MrDoc
  11. MFC中SetTimer函数
  12. 如何在Windows命令行窗口复制和粘贴?
  13. 极简短网址链接生成系统网站源码
  14. unity3d 取锚点位置_《王者荣耀》破晓之心碎片在哪 破晓之心碎片位置介绍
  15. 2022 年最佳开源软件出炉
  16. 安卓 OpenGLES 魔方
  17. Scrapy爬取豆瓣读书全站
  18. 七、jQuery动画特效(二)
  19. android 清华镜像,清华镜像网站下载android源码并编译
  20. 我的资源里边有好东西(gmt、panoply等等)

热门文章

  1. 栈与队列1——设计getMin功能的栈
  2. Elasticsearch创建雇员目录
  3. 云计算究竟是什么呢?“汇新杯”新兴科技成果专项赛之——云计算
  4. 测试 ClownFish、CYQ、Entity Framework、Moon、MySoft、NHibernate、PDF、XCode数据访问组件性能...
  5. 三层交换机与路由器的比较
  6. java queue size_Java中的PriorityQueue size() 方法 - Break易站
  7. pcre安装_Nginx学习_第一期_安装及安装问题解决
  8. layui 横向表单_对layui中表单元素的使用详解
  9. 如何链接两个名字一样动态库
  10. 51单片机怎么学啊?有推荐的网课和书籍么?