从python3.6开始,引入了新的字符串格式化方式,f-字符串. 这使得格式化字符串变得可读性更高,更简洁,更不容易出现错误而且速度也更快.

在本文后面,会详细介绍f-字符串的用法. 在此之前,让我们先来复习一下python中字符串格式化的方法.

python中传统的字符串格式化方法.

在python3.6之前,我们有两种方式可以用来格式化字符串.

  • 占位符+%的方式
  • str.format()方法

首先复习一下这两种方式的使用方法以及其短板.

占位符+%的方式

这种方式算是第0代字符串格式化的方法,很多语言都支持类似的字符串格式化方法. 在python的文档中,我们也经常看到这种方式.

但是!!!
BUT!!!

占位符+%的方式并不是python推荐的方式.

Note The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer formatted string literals, the str.format() interface, or template strings may help avoid these errors. Each of these alternatives provides their own trade-offs and benefits of simplicity, flexibility, and/or extensibility.(Python3 doc)

文档中也说了,这种方式对于元组等的显示支持的不够好. 而且很容易产生错误.

而且不符合python代码简洁优雅的人设...

「如何使用占位符+%的方式」

如果你接触过其他的语言,这种方式使用起来会有一种诡异的亲切感,这种亲切感会让你抓狂,内心会暗暗的骂上一句,艹,又是这德行...(这句不是翻译,是我的个人感觉,从来都记不住那么多数据类型的关键字...)


In [1]: name='Eric'

In [2]: 'Hello,%s'%name

Out[2]: 'Hello,Eric'

如果要插入多个变量的话,就必须使用元组.像这样


In [3]: name='Eric'

In [4]: age=18

In [5]: 'Hello %s,you are %d.'%(name,age)

Out[5]: 'Hello Eric,you are 18.'

「为什么说占位符+%的方式不是最好的办法(个人认为是这种方式是一种最操蛋的操作)」

上面有少量的变量需要插入到字符串的时候,这种办法还行. 但是一旦有很多变量需要插入到一个长字符串中...比如...


In [6]: first_name = "Eric"
...: last_name = "Idle"
...: age = 74
...: profession = "comedian"
...: affiliation = "Monty Python" In [7]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)


Out[7]: 'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

像上面这个例子,代码可读性就很差了.(对读和写的人都是一种折磨...)

使用str.format()的方式

在python2.6之后,引入了str.format()函数,可以用来进行字符串的格式化. 它通过调用对象的__format__()方法(PEP3101中定义)来将对象转化成字符串.

在str.format()方法中,通过花括号占位的方式来实现变量插入.


In [8]: 'hello,{}. You are {}.'.format(name,age)

Out[8]: 'hello,Eric. You are 74.'

甚至可以给占位符加索引.


In [9]: 'hello,{1}. You are {0}.'.format(age,name)

Out[9]: 'hello,Eric. You are 74.'

如果要在占位符中使用变量名的话,可以像下面这样


In [10]: person={'name':'Eric','age':74}

In [11]: 'hello,{name}. you are {age}'.format(name=person['name'],age=person['age'])

Out[11]: 'hello,Eric. you are 74'

当然对于字典来说的话,我们可以使用**的小技巧.


In [15]: 'hello,{name}. you are {age}'.format(**person)

Out[15]: 'hello,Eric. you are 74'

str.format()方法对于%的方式来说已经是一种很大的提升了. 但是这并不是最好的方式.

「为什么format()方法不是最好的方式」
相比使用占位符+%的方式,format()方法的可读性已经很高了. 但是同样的,如果处理含有很多变量的字符串的时候,代码会变得很冗长.



>>> first_name = "Eric"

>>> last_name = "Idle"

>>> age = 74

>>> profession = "comedian"

>>> affiliation = "Monty Python"

>>> print(("Hello, {first_name} {last_name}. You are {age}. " +

>>> "You are a {profession}. You were a member of {affiliation}.") \

>>> .format(first_name=first_name, last_name=last_name, age=age, \

>>> profession=profession, affiliation=affiliation))
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

当然,我们也可以通过字典的方式直接传入一个字典来解决代码过长的问题. 但是,python3.6给我们提供了更便利的方式.

f-字符串,一种新的增强型字符串格式化方式

这种新的方式在PEP498中定义.(原文写到这里的时候,作者可能疯了,balabla说了一长串,冷静的我并没有翻译这些废话...)
这种方式也被叫做formatted string literals.格式化的字符串常亮...ummm...应该是这么翻译吧...

这种方式在字符串开头的时候,以f标识,然后通过占位符{}+变量名的方式来自动解析对象的__format__方法. 如果想了解的更加详细,可以参考python文档

一些简单的例子

「使用变量名作为占位符」


In [16]: name = 'Eric'

In [17]: age=74

In [18]: f'hello {name}, you are {age}'

Out[18]: 'hello Eric, you are 74'

「这里甚至可以使用大写的F」


In [19]: F'hello {name}, you are {age}'

Out[19]: 'hello Eric, you are 74'

你以为这就完了吗?

不!

事情远不止想象的那么简单...

在花括号里甚至可以执行算数表达式


In [20]: f'{2*37}'

Out[20]: '74'

如果数学表达式都可以的话,那么在里面执行一个函数应该不算太过分吧...


In [22]: def to_lowercase(input):
...: return input.lower()
...:

In [23]: name = 'ERIC IDLE'

In [24]: f'{to_lowercase(name)} is funny'

Out[24]: 'eric idle is funny'

你以为这就完了吗?

不!

事情远不止想象的那么简单...

这玩意儿甚至可以用于重写__str__()和__repr__()方法.


class Comedian:
def __init__(self, first_name, last_name, age):
self.first_name = first_name
self.last_name = last_name
self.age = age
<span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">__str__</span><span class="hljs-params" style="line-height: 26px;">(self)</span>:</span>
<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"<span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.first_name}</span> <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.last_name}</span> is <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.age}</span>."</span> <span class="hljs-function" style="line-height: 26px;"><span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">def</span> <span class="hljs-title" style="color: #61aeee; line-height: 26px;">__repr__</span><span class="hljs-params" style="line-height: 26px;">(self)</span>:</span>
<span class="hljs-keyword" style="color: #c678dd; line-height: 26px;">return</span> <span class="hljs-string" style="color: #98c379; line-height: 26px;">f"<span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.first_name}</span> <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.last_name}</span> is <span class="hljs-subst" style="color: #e06c75; line-height: 26px;">{self.age}</span>. Surprise!"</span>

>>> new_comedian = Comedian("Eric", "Idle", "74")


>>> f"{new_comedian}"'Eric Idle is 74.'

关于__str__()方法和__repr__()方法. 这是对象的两个内置方法.__str()__方法用于返回一个便于人类阅读的字符串. 而__repr__()方法返回的是一个对象的准确释义. 这里暂时不做过多介绍. 如有必要,请关注公众号吾码2016(公众号:wmcoding)并发送str_And_repr

默认情况下,f-关键字会调用对象的__str__()方法. 如果我们想调用对象的__repr__()方法的话,可以使用!r



>>> f"{new_comedian}"
'Eric Idle is 74.'

>>> f"{new_comedian!r}"
'Eric Idle is 74. Surprise!'

更多详细内容可以参考这里

多个f-字符串占位符

同样的,我们可以使用多个f-字符串占位符.


>>> name = "Eric"

>>> profession = "comedian"

>>> affiliation = "Monty Python"

>>> message = (
... f"Hi {name}. "
... f"You are a {profession}. "
... f"You were in {affiliation}."
... )

>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

但是别忘了,在每一个字符串前面都要写上f

同样的,在字符串换行的时候,每一行也要写上f.


>>> message = f"Hi {name}. " \
... f"You are a {profession}. " \
... f"You were in {affiliation}."...

>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

但是如果我们使用"""的时候,不需要每一行都写.


>>> message = f"""
... Hi {name}.
... You are a {profession}.
... You were in {affiliation}.
... """
...

>>> message
'\n Hi Eric.\n You are a comedian.\n You were in Monty Python.\n'

关于f-字符串的速度

f-字符串的f可能代表的含义是fast,因为f-字符串的速度比占位符+%的方式和format()函数的方式都要快.因为它是在运行时计算的表达式而不是常量值.(那为啥就快了呢...不太懂啊...)

“F-strings provide a way to embed expressions inside string literals, using a minimal syntax. It should be noted that an f-string is really an expression evaluated at run time, not a constant value.
In Python source code, an f-string is a literal string, prefixed with f, which contains expressions inside braces. The expressions are replaced with their values.”(PEP498)

(官方文档,咱不敢翻,大意就是f-字符串是一个在运行时参与计算的表达式,而不是像常规字符串那样是一个常量值)

在运行时,花括号内的表达式在其自己的作用域内求职,单号和字符串的部分拼接到一起,然后返回.

下面我们来看一个速度的对比.

import timeit

time1 = timeit.timeit("""name = 'Eric'\nage =74\n'%s is %s'%(name,age)""",number=100000)

time2 = timeit.timeit("""name = 'Eric'\nage =74\n'{} is {}'.format(name,age)""",number=100000)

time3 = timeit.timeit("""name = 'Eric'\nage =74\nf'{name} is {age}'""",number=100000)

从结果上看的话,f-字符串的方式速度要比其他两种快.

0.030868000000000007
0.03721939999999996
0.0173276

f-字符串的一些细节问题

「引号的问题」
在f-字符串中,注意成对的引号使用.


f"{'Eric Idle'}"
f'{"Eric Idle"}'
f"""Eric Idle"""
f'''Eric Idle'''

以上这几种引号方式都是支持的. 如果说我们在双引号中需要再次使用双引号的时候,就需要进行转义了.
f"The \"comedian\" is {name}, aged {age}."

「字典的注意事项」

在字典使用的时候,还是要注意逗号的问题.


>>> comedian = {'name': 'Eric Idle', 'age': 74}

>>> f"The comedian is {comedian['name']}, aged {comedian['age']}."

>>> f'The comedian is {comedian['name']}, aged {comedian['age']}.'

比如上面两条语句,第三句就是有问题的,主要还是引号引起的歧义.

「花括号」
如果字符串中想使用花括号的话,就要写两个花括号来进行转义. 同理,如果想输出两个花括号的话,就要写四个...


>>> f"{{74}}"'{74}'

>>> f"{{{{74}}}}"

「反斜杠」
反斜杠可以用于转义. 但是!!!BUT!!!在f-字符串中,不允许使用反斜杠.


>>> f"{\"Eric Idle\"}"
File "<stdin>", line 1
f"{\"Eric Idle\"}"
^SyntaxError: f-string expression part cannot include a backslash

像上面这个的解决办法就是


>>> name = "Eric Idle"

>>> f"{name}"'Eric Idle'

「行内注释」
f-字符串表达式中不允许使用#符号.

总结和参考资料

我们依旧可以使用老的方式进行字符串格式化输出. 但是通过f-字符串,我们现在有了一种更便捷,更快,可读性更高的方式. 根据python教义,Zen of Python:

「there should be one– and preferably only one –obvious way to do it.」
(编程还编出哲理来了...实在不会翻,有一种醍醐灌顶的感觉,内心浮现一个声音,卧槽!好有道理,仿佛自己升华了,但是仔细想想...这句话到底啥意思呢...)

更多的参考资料(我也只是写在这里,反正我是没有闲心看它的...):

[翻译]python3中新的字符串格式化方法-----f-string的更多相关文章

  1. 快速理解Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容的区别

    <Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容有何不同?>老猿介绍了二者的区别,为了快速理解,老猿在此使用另外一种方式补充说明一下: 1.使用%r是调用objec ...

  2. Python中使用百分号占位符的字符串格式化方法中%s和%r的输出内容有何不同?

    Python中使用百分号占位符的字符串格式化方法中%s和%r表示需要显示的数据对应变量x会以str(x)还是repr(x)输出内容展示. 关于str和repr的关系请见: <Python中rep ...

  3. python字符串格式化方法 format函数的使用

      python从2.6开始支持format,新的更加容易读懂的字符串格式化方法, 从原来的% 模式变成新的可读性更强的 花括号声明{}.用于渲染前的参数引用声明, 花括号里可以用数字代表引用参数的序 ...

  4. Delphi 中Format的字符串格式化使用说明(转)

    源:Delphi 中Format的字符串格式化使用说明(转) 一.Format函数的用法 Format是一个很常用,却又似乎很烦的方法,本人试图对这个方法的帮助进行一些翻译,让它有一个完整的概貌,以供 ...

  5. 第3.8节 Python百分号占位符的字符串格式化方法

    一.    概念         格式化字符串就是将一些变量转换为字符串并按一定格式输出字符串,包括指定字符的位置.对齐方式.空位补充方式等.Python提供了多种字符串格式设置方法.本节先介绍一种简 ...

  6. (数据科学学习手札131)pandas中的常用字符串处理方法总结

    本文示例代码及文件已上传至我的Github仓库https://github.com/CNFeffery/DataScienceStudyNotes 1 简介 在日常开展数据分析的过程中,我们经常需要对 ...

  7. python的三种字符串格式化方法

    1.最方便的 print 'hello %s and %s' % ('df', 'another df') 但是,有时候,我们有很多的参数要进行格式化,这个时候,一个一个一一对应就有点麻烦了,于是就有 ...

  8. 7. python 字符串格式化方法(2)

    7. python 字符串格式化方法(2) 紧接着上一章节,这一章节我们聊聊怎样添加具体格式化 就是指定替换字段的大小.对齐方式和特定的类型编码,结构如下: {fieldname!conversion ...

  9. 7. python 字符串格式化方法(1)

    7. python 字符串格式化方法(1) 承接上一章节,我们这一节来说说字符串格式化的另一种方法,就是调用format() >>> template='{0},{1} and {2 ...

随机推荐

  1. chromosome interaction mapping|cis- and trans-regulation|de novo|SRS|LRS|Haplotype blocks|linkage disequilibrium

    Dissecting evolution and disease using comparative vertebrate genomics-The sequencing revolution   s ...

  2. vue打包成app后,背景图片不显示

    问题: 在使用npm run build 打包后, 如果在页面中使用img标签引入,打包后的路径是由index.html开始访问的,真正访问的是Static/img/图片名, 是正确的, 但是写在cs ...

  3. Canal监控Mysql同步到Redis(菜鸟也能搭建)

    首先要Canal服务端下载:链接: https://pan.baidu.com/s/1FwEnqPC1mwNXKRwJuMiLdg 密码: r8xf 连接数据库的时候需要给予连接数据库权限:在my.i ...

  4. 43)PHP,mysql_fetch_row 和mysql_fetch_assoc和mysql_fetch_array

    mysql_fetch_row   提取的结果是没有查询中的字段名了(也就是没有键id,GoodsName,只有值),如下图: mysql_fetch_assoc 提取的结果有键值,如下图: mysq ...

  5. python Pandas Profiling 一行代码EDA 探索性数据分析

    文章大纲 1. 探索性数据分析 代码样例 效果 解决pandas profile 中文显示的问题 1. 探索性数据分析 数据的筛选.重组.结构化.预处理等都属于探索性数据分析的范畴,探索性数据分析是帮 ...

  6. rest framework-序列化-长期维护

    ###############   表结构    ############### from django.db import models class Book(models.Model): titl ...

  7. linux的进程和管道符(二)

    回顾:进程管理:kill killall pkill问题:1.pkill -u root 禁止2.用户名不要用数字开头或者纯数字windows的用户名不要用中文3.pokit/etc/passwd 6 ...

  8. python语法基础-基础-运算符

    ############################################ Python语言支持以下类型的运算符: 算术运算符 比较(关系)运算符 赋值运算符 逻辑运算符 位运算符 成员 ...

  9. docker E: Unable to locate package nginx

    在使用docker容器时,有时候里边没有安装vim,敲vim命令时提示说:vim: command not found,这个时候就需要安装vim,可是当你敲apt-get install vim命令时 ...

  10. MySQL之数据存储引擎

    1.什么是存储引擎: 现实生活中我们用来存储数据的文件有不同的类型,每种文件类型对应各自不同的处理机制:比如处 理文本用txt类型,处理表格用excel,处理图片用png等,数据库中的表也应该有不同的 ...