Python3 格式化字符串

在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formattingstr.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. tensorflow mac安装方法

    480  pip install https://storage.googleapis.com/tensorflow/mac/tensorflow-0.5.0-py2-none-any.whl 481 ...

  2. check process id exists

    kill -0 pid sending the signal 0 to a given PID just checks if any process with the given PID is run ...

  3. redhat6.5 linux 安装mysql5.6.27

    1.yum安装mysql(root身份),适用于红帽6.5 yum install mysql-server mysql-devel mysql -y 如没有配置yum,请参见博客:http://ww ...

  4. 【cocos2d-js官方文档】事件分发监听机制(摘录)

    简介 游戏开发中一个很重要的功能就是交互,如果没有与用户的交互,那么游戏将变成动画,而处理用户交互就需要使用事件监听器了. 总概: 事件监听器(cc.EventListener) 封装用户的事件处理逻 ...

  5. css抖动动画

    button{ animation: beat 6s ease 0s infinite normal; } @keyframes beat { 0% { transform: translateY(0 ...

  6. node.js连接MongoDB数据库,db.collection is not a function完美解决

    解决方法一. mongodb数据库版本回退: 这个错误是出在mongodb的库中,在nodejs里的写法和命令行中的写法不一样,3.0的api已经更新和以前的版本不不一样,我们在npm中没指定版本号的 ...

  7. java资料共享

    1.javascript视频教程 链接: http://pan.baidu.com/s/1gd57FVH 密码: d9ei 2.JPA视频教程 链接: http://pan.baidu.com/s/1 ...

  8. beego 初体验 - orm

    goland Terminal运行命令: go get github.com/astaxie/beego/orm 安装go mysql驱动: go get github.com/go-sql-driv ...

  9. 如何简单地理解Python中的if __name__ == '__main__'(https://blog.csdn.net/yjk13703623757/article/details/77918633)

    1. 摘要 通俗的理解__name__ == '__main__':假如你叫小明.py,在朋友眼中,你是小明(__name__ == '小明'):在你自己眼中,你是你自己(__name__ == '_ ...

  10. Yii restful api跨域

    问题:NO 'Access-Control_Allow-Origin' header is present on the requested resource. 解决方案 <?php names ...