笔记-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. SVN中如何去除版本控制器

    SVN,大家都熟悉,做项目都知道,不知道你有没有遇到每次提交的代码的时候,都会把bin和obj自动生成的文件夹提交SVN服务器上 其实这里都不需要提交,每次生成都提交,可能还会容易冲突,如何不让bin ...

  2. 初始Mybatis,好累,自己感觉自己快坚持不了了

    Mybatis1.持久化 持久化,就是内存数据和硬盘数据状态的转换 2.ORM思想Object Relation Mapping 对象关系映射 3.MyBatis入门案例 3.1导入jar包 依赖 & ...

  3. Java 8新特性--Lambda表达式作为返回值

    lambda表达式作为方法的返回值:

  4. I/O————File对象

    File文件对象 文件和文件夹都是用File代表 创建一个文件对象,(并不会有真正的文件或文件夹被创建) File f1 = new File("d:/lolfilder"); S ...

  5. CF739B

    深搜的过程中保存路径,二分路径中满足要求的区段.不必将每个节点的ans加1,只需将合法区段末尾加1同时将开头减1来表示并保存在一个“前缀”数组中即可.最后再dfs一次累加得到答案. #include ...

  6. cf1028C. Rectangles(前缀和)

    题意 给出$n$个矩形,找出一个点,使得至少在$n$个矩阵内 Sol 呵呵哒,昨天cf半夜场,一道全场切的题,我没做出来..不想找什么理由,不会做就是不会做.. 一个很显然的性质,如果存在一个点 / ...

  7. 洛谷P2827 蚯蚓(单调队列)

    题意 初始时有$n$个蚯蚓,每个长度为$a[i]$ 有$m$个时间,每个时间点找出长度最大的蚯蚓,把它切成两段,分别为$a[i] * p$和$a[i] - a[i] * p$,除这两段外其他的长度都加 ...

  8. BeanUtils 工具类

    一.BeanUtils 概述     BeanUtils 是阿帕奇提供的一套专门用于将一些数据封装到java对象中的工具类;          名词:javaBean:特定格式的java类称为java ...

  9. 字符串、String等转换

    (1) String 转换为字符串 例:String s = "abcde";char[] a = s.toCharArray(); (2) 字符串转换为Stringchar[] ...

  10. 解决 FusionCharts3.2.1 首页无法载入的问题

    在实际项目中测试FusionCharts3.2.1时,发现首次载入无法正常载入,第二次载入就恢复正常!   原因:FusionCharts ID与变量名重复   以下是正常写法: var member ...