一、格式化字符串的方式:

1、字符串表达式:

语法格式:‘%s’ % var 或 ‘%s %d’ % (var1, var2)

说明:%s、%d等为格式类型说明符

例子:

>>> 'this is a %s' % ('pear')
'this is a pear'
>>> 'there are %d %s and %d %s' % (2, 'pear', 5, 'apple')
'there are 2 pear and 5 apple'

#使用字典格式
>>> 'there are %(count)d %(fruit)s' % {'count':5, 'fruit':'apples'}
'there are 5 apples'

2、字符串format方法:

语法格式:str.format()

说明:使用字符串的format方法

例子:

#使用相对位置参数
>>> astring = 'there are {} {} and {} {}'
>>> astring.format(2, 'pears', 5, 'apples')
'there are 2 pears and 5 apples'

#使用绝对位置参数
>>> astring = 'there are {0} {1} and {0} {2}'
>>> astring.format(2, 'pears', 'apples')
'there are 2 pears and 2 apples'

#使用关键字参数
>>> astring = 'there are {count} {fruit1} and {count} {fruit2}'
>>> astring.format(count=2, fruit1='pears', fruit2='apples')
'there are 2 pears and 2 apples'

3、format内建函数:

语法格式:format(value[, format_spec])

说明:第1个参数为字符串、数字等,第2个参数为格式说明符,省略格式说明符,就相当于str(value)

例子:

#缺省类型为s(字符串),可以省略不写
>>> format('^表示居中,10表示宽度,不够的位用#填充','#^10')
'^表示居中,10表示宽度,不够的位用#填充'

>>> format(123,'b')
'1111011'
>>> format(123,'#b')
'0b1111011'
>>>

4、已格式化的字符串直接量(也就是一个带格式的字符串,简称f-strings):

语法格式:f'{expression[:format-spicifier]}'

说明:类似于r'string'、b'byte sequence'的风格,f也可以是大写的F,表达式expression可以是直接量、变量,对象属性,函数调用、模块方法执行等,还可以结合!s或!r对表示执行str或repr函数。格式化说明符可以省略。

例子:

>>> f'{10:b}'
'1010'
>>> f'{10:x}'
'a'
>>> f'{12:x}'
'c'
>>> f'{12:X}'
'C'
>>> f'{12:#X}'
'0XC'
>>> f'{12:02X}'
'0C'
>>> f'{12:2X}'
' C'
>>> F'this is a hex number {12:#2X} and an octet number {29:#o}'
'this is a hex number 0XC and an octet number 0o35'
>>> import random
>>> F'this is a hex number {random.randint(100,500):#2X} and an octet number {29:#o}'
'this is a hex number 0X8A and an octet number 0o35'
>>> import math
>>> print(f'The value of pi is approximately {math.pi:.3f}.')
The value of pi is approximately 3.142.
#表示式为变量,效果类似于shell字符串中变量替换,同时还可以在替换后进行格式化
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print(f'{name:10} ==> {phone:10d}')
...
Sjoerd ==> 4127
Jack ==> 4098
Dcab ==> 7678
>>> animals = 'eels'
>>> print(f'My hovercraft is full of {animals}.')
My hovercraft is full of eels.
>>> print(f'My hovercraft is full of {animals!r}.')
My hovercraft is full of 'eels'.

5、字符串手动格式化

语法格式:str.rjust([width][, padding-char])、str.rjust([width][, padding-char])、center([width][, padding-char])、str.zfill()

说明:字符串的左、右、中对齐方法,第1个参数为宽度,第2个为字符串宽度小于指定宽度后填充的字符,缺省为空格。str.zfill()用于数字串填充0

例子:

>>> '12'.zfill(5)
'00012'
>>> '-3.14'.zfill(7)
'-003.14'
>>> '3.14159265359'.zfill(5)
'3.14159265359'
>>> 'this is a left indent string'.ljust(40)
'this is a left indent string '
>>> 'this is a left indent string'.ljust(40,'-')
'this is a left indent string------------'
>>>

二、通用标准格式化说明符及特殊格式说明符如下:

format_spec     ::=  [[fill]align][sign][#][0][width][grouping_option][.precision][type]
fill ::= <any character>
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= digit+
grouping_option ::= "_" | ","

precision ::= digit+
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X"

旧的字符串表达式格式:

>>> '%#x' % 255, '%x' % 255, '%X' % 255
('0xff', 'ff', 'FF')
>>> format(255, '#x'), format(255, 'x'), format(255, 'X')
('0xff', 'ff', 'FF')
>>> f'{255:#x}', f'{255:x}', f'{255:X}'
('0xff', 'ff', 'FF')

表示一个百分号%使用特殊类型符%:

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

使用时间专用格式:

>>> 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'

嵌套参数和更复杂例子:

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

更详细的格式化说明可以参见python3.7.1参考手册的章节:7.1. Fancier Output Formatting

python之格式化字符串速记整理的更多相关文章

  1. Python datetime 格式化字符串:strftime()

    Python datetime 格式化字符串:strftime()   Python 的datetime模块 其实就是date和time 模块的结合, 常见的属性方法都比较常用 比如: datetim ...

  2. Python 【格式化字符串】

    print('血量:'+str(player_life)+' 攻击:'+str(player_attack)) 第一种格式化字符串 print('血量:%s 攻击:%s' % (player_life ...

  3. Python 3 格式化字符串的几种方法!

    Python 3 格式化字符串的几种方法! %s和%d,%s是用来给字符串占位置,%d是给数字占位置,简单解释下: a = 'this is %s %s' % ('an','apple') 程序输出的 ...

  4. 茴香豆的“茴”有四种写法,Python的格式化字符串也有

    茴香豆的"茴"有四种写法,Python的格式化字符串也有 茴香豆的"茴"有四种写法,Python的格式化字符串也有 被低估的断言 多一个逗号,少一点糟心事 上下 ...

  5. Python 的格式化字符串format函数

    阅读mattkang在csdn中的博客<飘逸的python - 增强的格式化字符串format函数>所做笔记 自从python2.6开始,新增了一种格式化字符串的函数str.format( ...

  6. Python 中格式化字符串 % 和 format 两种方法之间的区别

    Python2.6引入了 format 格式化字符串的方法,现在格式化字符串有两种方法,就是 % 和 format ,具体这两种方法有什么区别呢?请看以下解析. # 定义一个坐标值 c = (250, ...

  7. python format格式化字符串

    自python2.6开始,新增了一种格式化字符串的函数str.format() 语法 它通过{}和:来代替%. “映射”示例 通过位置 In [1]: '{0},{1}'.format('kzc',1 ...

  8. Python:格式化字符串的几种方式

    1.% 'abc%s'%'123' 'abc123' 'abc%s%s'%('123','456') 'abc123456' 当变量v是一个Tuple.List且其中元素数量和字符串中%数量相同时,可 ...

  9. python - 平方根格式化 + 字符串分段组合

    题目来源:python123 平方根格式化 描述 获得用户输入的一个整数a,计算a的平方根,保留小数点后3位,并打印输出.‪‬‪‬‪‬‪‬‪‬‮‬‫‬‪‬‪‬‪‬‪‬‪‬‪‬‮‬‪‬‫‬‪‬‪‬‪‬‪ ...

随机推荐

  1. JavaSE15-集合·其二

    1.Set集合 1.1 Set集合概述和特点 Set集合的特点 元素存取无序 没有索引.只能通过迭代器或增强for循环遍历 不能存储重复元素 1.2 哈希值 哈希值简介 是JDK根据对象的地址或者字符 ...

  2. Maven笔记之核心概念及常用命令

    Maven的核心概念 Maven是一款服务于java平台的自动化构建工具. 自动化构建工具还有:make->ant->maven->gradle       1.约定的目录  2.P ...

  3. 2020-2021-1 20209307《Linux内核原理与分析》第六周作业

    这个作业属于哪个课程 <2020-2021-1Linux内核原理与分析)> 这个作业要求在哪里 <2020-2021-1Linux内核原理与分析第六周作业> 这个作业的目标 & ...

  4. c++日常小问题

    语法解析问题. 当给一个变量构造函数传递一个临时变量,而不是命名的变量,c++编译器会将其解析为函数声明,而不是类型对象的定义. class hello { void operator()() { s ...

  5. qs的工具方法讲解

    简单来说,qs 是一个增加了一些安全性的查询字符串解析和序列化字符串的库. 今天在学习同事的代码, 在学习过程中遇到了这样一句代码 研究了很久,只了解了个大概,后面慢慢的用熟练只会,想着做个总结,温习 ...

  6. MSSQL数据库一对多和多对一查询的转换

    前言 处理一对多关系,有两种方式 (1)创建关系表,将对应关系保存在物理表中. (2)表中添加一个字段,将多关系的值以特殊符号隔开进行保存. 本例使用的就是,以逗号隔开(InterestID='1,2 ...

  7. [.NET] - 初步认识AutoMapper

    初步认识AutoMapper AutoMapper 初步认识AutoMapper 前言 手动映射 使用AutoMapper 创建映射 Conventions 映射到一个已存在的实例对象   前言 通常 ...

  8. CSS中margin:auto什么意思?margin:auto属性的用法详解

    我们都知道使用margin:auto可以让元素水平居中的.但你有没有想过使用margin:auto可以让元素水平居中的原因,要回答这个问题,我们首先需要看一下margin:auto的工作原理.auto ...

  9. 持续提升程序员幸福指数——使用abp vnext设计一款面向微服务的单体架构

    可能你会面临这样一种情况,在架构设计之前,你对业务不甚了解,需求给到的也模棱两可,这个时候你既无法明确到底是要使用单体架构还是使用微服务架构,如果使用单体,后续业务扩展可能带来大量修改,如果使用微服务 ...

  10. CentOS7下常用安装服务软件源码编译安装方式的介绍

    简介:介绍源码编译安装软件包的管理 源码安装优点:编译安装过程,可以设定参数,指定安装目录,按照需求进行安装,指定安装的版本,灵活性比较大. 源码安装的缺点:需要对依赖包一个一个的进行安装,不敢随便升 ...