Python3 格式化字符串
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 格式化字符串的更多相关文章
- Python3之字符串格式化format函数详解(上)
概述 在Python3中,字符串格式化操作通过format()方法或者f’string’实现.而相比于老版的字符串格式化方式,format()方法拥有更多的功能,操作起来更加方便,可读性也更强.该函数 ...
- python3 f-string格式化字符串的高级用法
从Python 3.6开始,f-string是格式化字符串的一种很好的新方法.与其他格式化方式相比,它们不仅更易读,更简洁,不易出错,而且速度更快! 在Python 3.6之前,有两种将Python表 ...
- Python 中格式化字符串 % 和 format 两种方法之间的区别
Python2.6引入了 format 格式化字符串的方法,现在格式化字符串有两种方法,就是 % 和 format ,具体这两种方法有什么区别呢?请看以下解析. # 定义一个坐标值 c = (250, ...
- Python中应该使用%还是format来格式化字符串?
转载自http://www.cnblogs.com/liwenzhou/p/8570701.html %的特点是,前面有几个%,后面的括号里就得有几个参数,如果只有一个%,括号可以省略 基本格式 'a ...
- Python3.x - 字符串
Python3 字符串 字符串是 Python 中最常用的数据类型.我们可以使用引号( ' 或 " )来创建字符串. var1 = 'hello world' var2 = "he ...
- Python中使用%还是format来格式化字符串?
Python中应该使用%还是format来格式化字符串? %还是format Python中格式化字符串目前有两种阵营:%和format,我们应该选择哪种呢? 自从Python2.6引入了form ...
- Qt sprintf_s函数格式化字符串出错
Qt sprintf_s函数格式化字符串出错 问题的出现: 我在VS上用c C++写的跨平台的函数 移植到Qt 上面 出现sprintf_s 函数格式化出错. 开始以为是编码问题 反复查找Qt乱码问 ...
- format格式化字符串
假如想要表达这样一条语句:李明今年十二岁 输出这样一条语句 name = 'LiMing' age = 12 print( name + 'is' + age + 'years old') #输出 L ...
- Python - 格式化字符串的用法
0. 摘要 Python支持多种格式化字符串的方法,包括%-fromatting.str.format().f-strings三种,f-strings是Python3.6以后出现的一种新方法,相比其他 ...
随机推荐
- http协议下载文件
通过在 URL 上调用 openConnection 方法创建连接对象.(HttpURLConnection conn = (HttpURLConnection)new URL("网址&qu ...
- [LeetCode] 504. Base 7_Easy tag: Math
Given an integer, return its base 7 string representation. Example 1: Input: 100 Output: "202&q ...
- golang配置
配置使用yaml,使用了github上一个configor的库.理由如下: 1. 支持多种格式 2. ORM,自动给变量赋值,不用写太多的代码 3. 但是他支持shell env配置,我怕与运行的环境 ...
- url传输编码
首先:协议规范,RFC 1738,定义url地址中不能包含除:0-9,a-zA-Z,- 之外的字符,即,如URL中包含特殊字符,如$-_.+!*’(), 都要编码. 关于为什么如此定义,有如下几个原因 ...
- docker同步时区时间
在Docker容器创建好之后,可能会发现容器时间跟宿主机时间不一致,这就需要同步它们的时间,让容器时间跟宿主机时间保持一致.如下: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 ...
- Oracle推进SCN系列:使用oradebug在mount状态下推进SCN
环境:RHEL 6.5(x86-64) + Oracle 11.2.0.4 声明:推进SCN属于非常规恢复范畴,不建议非专业人员操作,否则后果自负. 需求:我这里演示下推进SCN 10W数量级,实际需 ...
- node.js初识07
之前有说过,nodejs是 没有web容器的,阿帕奇是自带的web容器,如果希望node达到阿帕奇的效果,即http://127.0.0.1:3000/a/b/c.html 出现这样的链接访问页面,所 ...
- POJ 2752 Seek the Name,Seek the Fame(KMP,前缀与后缀相等)
Seek the Name,Seek the Fame 过了个年,缓了这么多天终于开始刷题了,好颓废~(-.-)~ 我发现在家真的很难去学习,因为你还要陪父母,干活,做家务等等 但是还是不能浪费时间啊 ...
- C#字符串比较方法
用C#比较字符串有多种方法,如: 1. string.Compare(x,y);2. string.Equals(x,y) ; 如果要不区分大小写进行比较,则对应为:string.Compare(x, ...
- Java多线程-----创建线程的几种方式
1.继承Thread类创建线程 定义Thread类的子类,并重写该类的run()方法,该方法的方法体就是线程需要完成的任务,run()方法也称为线程执行体 创建Thread子类的实例,也就是创建 ...