python span.string函数_【转】python f-string

主要内容

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

在本文的最后,您将了解如何以及为什么今天开始使用f-string(后文称为F字符串)。

但首先, 我们要聊以下在F字符串出现之前我们怎么实现格式化字符的。

旧时代的格式化字符串

在Python 3.6之前,有两种将Python表达式嵌入到字符串文本中进行格式化的主要方法:%-formatting和str.format()。您即将看到如何使用它们以及它们的局限性。

Option #1: %-formatting

这是Python格式化的OG(original generation),伴随着python语言的诞生。您可以在Python文档中阅读更多内容。请记住,文档不建议使用%格式,其中包含以下注释:

“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 or the str.format() interface helps avoid these errors. These alternatives also provide more powerful, flexible and extensible approaches to formatting text.”

怎样使用 %-formatting

字符串对象具有使用%运算符的内置操作,您可以使用它来格式化字符串。以下是实践中的情况:

1

2

name = "Eric"

"Hello, %s." % name

'Hello, Eric.'

为了插入多个变量,您必须使用这些变量的元组。以下是你如何做到这一点:

1

2

3

name = "Eric"

age = 74

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

'Hello, Eric. You are 74.'

为什么 %-formatting不好用

上面刚刚看到的代码示例足够易读。但是,一旦你开始使用几个参数和更长的字符串,你的代码将很快变得不太容易阅读。事情已经开始显得有点凌乱:

1

2

3

4

5

6

7

first_name = "Eric"

last_name = "Idle"

age = 74

profession = "comedian"

affiliation = "Monty Python"

"Hello, %s %s. You are %s. You are a %s. You were a member of %s." %

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值