- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章浅析Python 中几种字符串格式化方法及其比较由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
起步 。
在 Python 中,提供了很多种字符串格式化的方式,分别是 %-formatting、str.format 和 f-string 。本文将比较这几种格式化方法.
%- 格式化 。
这种格式化方式来自于 C 语言风格的 sprintf 形式
1
2
|
name
=
"weapon"
"Hello, %s."
%
name
|
C 语言的给实话风格深入人心,通过 % 进行占位.
为什么 %-formatting不好 。
不好的地方在于,如果字符串较长或较多的参数,那么可读性就变得很差.
str.format 格式化 。
PEP-3101 带来了 str.format ,它是对 %-formatting 的改进。它使用正常的函数调用语法,并且可以通过对要转换为字符串的对象的 __format __() 方法进行扩展.
1
|
"Hello, {}. You are {}."
.
format
(name, age)
|
并支持字典形式传参,免于位置参数带来的麻烦:
1
|
"Hello, {name}. You are {age}."
.
format
(name
=
name, age
=
age)
|
这两种方式代码效果相同,只是第一种方法需要严格控制传入的参数位置,而第二种方法没有这种限制, 并增加了代码的可读性。各种技巧可查看 Format Specification Mini-Language 。
为什么 str.format() 并不好 。
虽然它解决了字符串冗长情况下的可读性,但需要对字典传参基本是要重写一遍变量名,不够优雅.
f-string 格式化 。
PEP-0498 带来了 f-string 方式,它从 Python3.6 开始支持。这种方式也是使用 __format__ 协议进行格式化.
1
2
3
|
name
=
"Eric"
age
=
74
f
"Hello, {name}. You are {age}."
|
语法上与 str.format() 类似,但更为简洁,当字符串较长时也不会繁琐。更强大的是它支持任意的表达式。我们可以在花括号内进行四则运算或函数调用等:f"{2 * 6}" 或者 f"{name.lower()} is funny" .
并且它性能也最好.
几种格式化方式性能比较 。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
import
timeit
def
add():
status
=
200
body
=
'hello world'
return
'Status: '
+
str
(status)
+
'\r\n'
+
body
+
'\r\n'
def
old_style():
status
=
200
body
=
'hello world'
return
'Status: %s\r\n%s\r\n'
%
(status, body)
def
formatter1():
status
=
200
body
=
'hello world'
return
'Status: {}\r\n{}\r\n'
.
format
(status, body)
def
formatter2():
status
=
200
body
=
'hello world'
return
'Status: {status}\r\n{body}\r\n'
.
format
(status
=
status, body
=
body)
def
f_string():
status
=
200
body
=
'hello world'
return
f
'Status: {status}\r\n{body}\r\n'
perf_dict
=
{
'add'
:
min
(timeit.repeat(
lambda
: add())),
'old_style'
:
min
(timeit.repeat(
lambda
: old_style())),
'formatter1'
:
min
(timeit.repeat(
lambda
: formatter1())),
'formatter2'
:
min
(timeit.repeat(
lambda
: formatter2())),
'f_string'
:
min
(timeit.repeat(
lambda
: f_string())),
}
print
(perf_dict)
|
结果
1
2
3
4
5
6
7
|
{
'add'
:
0.8815229000000002
,
'old_style'
:
0.6351808999999999
,
'formatter1'
:
0.7536176999999995
,
'formatter2'
:
1.2277180999999997
,
'f_string'
:
0.4891379000000011
}
|
f-string 格式化的方式性能最好.
为何 f-string 速度如此快 。
从指令来看,f'Status: {status}\r\n{body}\r\n' 翻译成:
1
2
3
4
5
6
7
8
|
8
LOAD_CONST
3
(
'Status: '
)
10
LOAD_FAST
0
(status)
12
FORMAT_VALUE
0
14
LOAD_CONST
4
(
'\r\n'
)
16
LOAD_FAST
1
(body)
18
FORMAT_VALUE
0
20
LOAD_CONST
4
(
'\r\n'
)
22
BUILD_STRING
5
|
正如指令中所示的,f-string 是运行时渲染的,底层中转成了类似 "Status: " + status+ "\r\n" + body + "\r\n" 的形式。正如 PEP-0498 中提到的
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. 。
而其他方式则是要先创建字符串常量值,再进行替换之类的操作.
总结 。
我们仍然可以使用以前的方式进行格式化,但在此推荐 f-string 方式,因为它使用更简洁,更易读且更方便,性能又更好,完全没理由拒绝啊.
从今天开始使用 f-string.
以上所述是小编给大家介绍的Python 中几种字符串格式化方法及其比较,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的! 。
原文链接:https://www.hongweipeng.com/index.php/archives/1806/ 。
最后此篇关于浅析Python 中几种字符串格式化方法及其比较的文章就讲到这里了,如果你想了解更多关于浅析Python 中几种字符串格式化方法及其比较的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我想了解 Ruby 方法 methods() 是如何工作的。 我尝试使用“ruby 方法”在 Google 上搜索,但这不是我需要的。 我也看过 ruby-doc.org,但我没有找到这种方法。
Test 方法 对指定的字符串执行一个正则表达式搜索,并返回一个 Boolean 值指示是否找到匹配的模式。 object.Test(string) 参数 object 必选项。总是一个
Replace 方法 替换在正则表达式查找中找到的文本。 object.Replace(string1, string2) 参数 object 必选项。总是一个 RegExp 对象的名称。
Raise 方法 生成运行时错误 object.Raise(number, source, description, helpfile, helpcontext) 参数 object 应为
Execute 方法 对指定的字符串执行正则表达式搜索。 object.Execute(string) 参数 object 必选项。总是一个 RegExp 对象的名称。 string
Clear 方法 清除 Err 对象的所有属性设置。 object.Clear object 应为 Err 对象的名称。 说明 在错误处理后,使用 Clear 显式地清除 Err 对象。此
CopyFile 方法 将一个或多个文件从某位置复制到另一位置。 object.CopyFile source, destination[, overwrite] 参数 object 必选
Copy 方法 将指定的文件或文件夹从某位置复制到另一位置。 object.Copy destination[, overwrite] 参数 object 必选项。应为 File 或 F
Close 方法 关闭打开的 TextStream 文件。 object.Close object 应为 TextStream 对象的名称。 说明 下面例子举例说明如何使用 Close 方
BuildPath 方法 向现有路径后添加名称。 object.BuildPath(path, name) 参数 object 必选项。应为 FileSystemObject 对象的名称
GetFolder 方法 返回与指定的路径中某文件夹相应的 Folder 对象。 object.GetFolder(folderspec) 参数 object 必选项。应为 FileSy
GetFileName 方法 返回指定路径(不是指定驱动器路径部分)的最后一个文件或文件夹。 object.GetFileName(pathspec) 参数 object 必选项。应为
GetFile 方法 返回与指定路径中某文件相应的 File 对象。 object.GetFile(filespec) 参数 object 必选项。应为 FileSystemObject
GetExtensionName 方法 返回字符串,该字符串包含路径最后一个组成部分的扩展名。 object.GetExtensionName(path) 参数 object 必选项。应
GetDriveName 方法 返回包含指定路径中驱动器名的字符串。 object.GetDriveName(path) 参数 object 必选项。应为 FileSystemObjec
GetDrive 方法 返回与指定的路径中驱动器相对应的 Drive 对象。 object.GetDrive drivespec 参数 object 必选项。应为 FileSystemO
GetBaseName 方法 返回字符串,其中包含文件的基本名 (不带扩展名), 或者提供的路径说明中的文件夹。 object.GetBaseName(path) 参数 object 必
GetAbsolutePathName 方法 从提供的指定路径中返回完整且含义明确的路径。 object.GetAbsolutePathName(pathspec) 参数 object
FolderExists 方法 如果指定的文件夹存在,则返回 True;否则返回 False。 object.FolderExists(folderspec) 参数 object 必选项
FileExists 方法 如果指定的文件存在返回 True;否则返回 False。 object.FileExists(filespec) 参数 object 必选项。应为 FileS
我是一名优秀的程序员,十分优秀!