Python3 格式化字符串

在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formatting和str.format()

一、%-formatting

name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)

注:这种格式不是很好,因为它是冗长的,会导致错误。

二、str.format()

str.format() 在Python 2.6中引入的。

(1)使用str.format(),替换字段用大括号标记:

"Hello, {}. You are {}.".format(name, age)
# 输出结果:'Hello, Eric. You are 74.'

(2)可以通过引用其索引来以任何顺序引用变量:

"Hello, {1}. You are {0}-{0}.".format(age, name)
# 输出结果:'Hello, Eric. You are 74-74.'

(3)如果插入变量名称,则会获得额外的能够传递对象的权限,然后在大括号之间引用参数和方法:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
# 输出结果:'Hello, Eric. You are 74.'

(4)可以使用**来用字典来完成这个巧妙的技巧:

person = {'name': 'Eric', 'age': 74}
"Hello, {name}. You are {age}.".format(**person)
# 输出结果:'Hello, Eric. You are 74.'

注:当处理多个参数和更长的字符串时,str.format()仍然可能非常冗长。

三、f-Strings

f-Strings是在Python 3.6开始加入标准库。也称为“格式化字符串文字”,F字符串是开头有一个f的字符串文字,以及包含表达式的大括号将被其值替换。

(1)f-Strings

name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
# 输出结果:'Hello, Eric. You are 74.'

(2)用大写字母F也是有效的:

name = "Eric"
age = 74
F"Hello, {name}. You are {age}."
# 输出结果:'Hello, Eric. You are 74.'

(3)可以调用函数

name = "Eric"
age = 74
f"{name.lower()} is funny."
# 输出结果:'eric is funny.' f"{2 * 37}"
# 输出结果:'74'

(4)可以使用带有f字符串的类创建对象

class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
def __str__(self):
return f"{self.first_name} {self.last_name} is {self.age}."
def __repr__(self):
return f"{self.first_name} {self.last_name} is {self.age}. Surprise!" new_comedian = Comedian("Eric", "Idle", "")
f"{new_comedian}"
# 输出结果;'Eric Idle is 74.' f"{new_comedian!r}"
# 输出结果:'Eric Idle is 74. Surprise!'

(5)多行f-string

message = (f"Hi {name}. "
f"You are a {profession}. "
f"You were in {affiliation}.")
# 输出结果:'Hi Eric. You are a comedian. You were in Monty Python.' message = (f"Hi {name}. "
"You are a {profession}. "
"You were in {affiliation}.")
# 输出结果:'Hi Eric. You are a {profession}. You were in {affiliation}.'

(6)使用"""

message = f"""
Hi {name}.
You are a {profession}.
You were in {affiliation}.
"""
# 输出结果:'\n Hi Eric. \n You are a comedian. \n You were in Monty Python.\n '

(7)性能

f字符串中的f也可以代表“速度快”。f-字符串是运行时渲染的表达式,而不是常量值。

速度比较:

%%timeit
name = "Eric"
age = 74
'%s is %s.' % (name, age)
# 202 ns ± 2.05 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %%timeit
name = "Eric"
age = 74
'{} is {}.'.format(name, age)
# 244 ns ± 5.52 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) %%timeit
name = "Eric"
age = 74
'{name} is {age}.'
# 14.4 ns ± 0.0121 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

(8)语法正确格式

f"{'Eric Idle'}"
# 输出结果:'Eric Idle'
f'{"Eric Idle"}'
# 输出结果:'Eric Idle'
f"""Eric Idle"""
# 输出结果:'Eric Idle'
f'''Eric Idle'''
# 输出结果:'Eric Idle'
f"The \"comedian<span class="string">" is {name}, aged {age}."
# 输出结果:'The "comedian" is Eric, aged 74.'

(9)字典

字典的键使用单引号,请记住确保对包含键的f字符串使用双引号。

comedian = {'name': 'Eric Idle', 'age': 74}
f"The comedian is {comedian['name']}, aged {comedian['age']}."
# 输出结果:'The comedian is Eric Idle, aged 74.'

(10)大括号

为了使字符串出现大括号,您必须使用双大括号:

f"{{74}}"
# 输出结果:'{74}' f"{{{{74}}}}"
# 输出结果:'{{74}}'

Python3 格式化字符串的更多相关文章

  1. Python3之字符串格式化format函数详解(上)

    概述 在Python3中,字符串格式化操作通过format()方法或者f’string’实现.而相比于老版的字符串格式化方式,format()方法拥有更多的功能,操作起来更加方便,可读性也更强.该函数 ...

  2. python3 f-string格式化字符串的高级用法

    从Python 3.6开始,f-string是格式化字符串的一种很好的新方法.与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快! 在Python 3.6之前,有两种将Python表 ...

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

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

  4. Python中应该使用%还是format来格式化字符串?

    转载自http://www.cnblogs.com/liwenzhou/p/8570701.html %的特点是,前面有几个%,后面的括号里就得有几个参数,如果只有一个%,括号可以省略 基本格式 'a ...

  5. Python3.x - 字符串

    Python3 字符串 字符串是 Python 中最常用的数据类型.我们可以使用引号( ' 或 " )来创建字符串. var1 = 'hello world' var2 = "he ...

  6. Python中使用%还是format来格式化字符串?

    Python中应该使用%还是format来格式化字符串?   %还是format Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了form ...

  7. Qt sprintf_s函数格式化字符串出错

    Qt sprintf_s函数格式化字符串出错 问题的出现: 我在VS上用c C++写的跨平台的函数 移植到Qt 上面 出现sprintf_s 函数格式化出错. 开始以为是编码问题  反复查找Qt乱码问 ...

  8. format格式化字符串

    假如想要表达这样一条语句:李明今年十二岁 输出这样一条语句 name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') #输出 L ...

  9. Python - 格式化字符串的用法

    0. 摘要 Python支持多种格式化字符串的方法,包括%-fromatting.str.format().f-strings三种,f-strings是Python3.6以后出现的一种新方法,相比其他 ...

随机推荐

  1. Apache 强制Http跳转Https

    找到网站根目录的.htaccess文件,添加如下代码 RewriteEngine On RewriteCond %{SERVER_PORT} RewriteRule ^(.*)$ https://%{ ...

  2. TVTK安装

    首先感觉到的一点就是在https://www.lfd.uci.edu/~gohlke/pythonlibs/#chaco这个比较受欢迎的下载Python库的网站上下载大于20mb的whl文件时就很可能 ...

  3. gerrit设置非小组成员禁止下载代码

    对gerrit有所了解的同学,都知道gerrit 是我们常用的一个来做代码审核的工具,其中的权限管理,是一个非常重要的环节,关于每个权限的使用范围,可以参考博客https://blog.csdn.ne ...

  4. Go linux 实践4

    这是目前学习的最难的Go demo例子 ***************************************** 如果能看懂,你就出师了,我的任务也就结束了 **************** ...

  5. Selenium基本使用(十三)测试中常见问题

    我们在使用selenium测试过程中,经常会遇到这样的问题: 1.frame或iframe <iframe id='frame1' name='frame1'> <input typ ...

  6. UGUI之Image使用以及技能释放CD

    顾名思义:Image就是用来显示图片的 Image中Image组件中有一个重要的熟悉:Image type

  7. composer----------composer基本命令和遇到一些问题解决方案

    1.composer跟xdebug有冲突,每次用composer命令的时候都要报xdebug的错误,去php的配置文件里面将xdebug注释掉就可以了,但是我注释掉了以后还是不行.找了半天才看到,我用 ...

  8. List<String> 2List <Long>

    public static List<Integer> CollStringToIntegerLst(List<String> inList){ List<Integer ...

  9. 基于MySQL提供的Yum repository安装MySQL5.6

    基于MySQL提供的Yum repository安装MySQL5.6 1:下载YUM包 1.1切换到root用户: 1)su - root 2)wget http://dev.mysql.com/ge ...

  10. [博客迁移]探索Windows Azure 监控和自动伸缩系列3 - 启用Azure监控扩展收集自定义监控数据

    上一篇我们介绍了获取Azure的监控指标和监控数据: http://www.cnblogs.com/teld/p/5113376.html 本篇我们继续:监控虚拟机的自定义性能计数器. 随着我们应用规 ...