一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python中格式化字符串的四种实现代码

时间:2020-05-26 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python中格式化字符串的四种实现代码,代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、%运算符格式化字符串

1. 如何使用

字符串对象都有一个使用%运算符完成的內置操作,可被用来格式化字符串。最简单的如:

In [11]: name = "Monty Python"
In [12]: "Hello, %s." % name
Out[12]: 'Hello, Monty Python.'

如果想要对一段字符串中插入多个变量进行格式化,则需要使用一个元组将待插入变量包在一起,如:

In [14]: name = "Monty Python"

In [15]: age = 100

In [16]: "Hello, %s. You are %d years old" % (name, age)
Out[16]: 'Hello, Monty Python. You are 100 years old'

2. 缺点概述

使用%运算符的方式来格式化字符串自Python语言诞生之日起就已存在,上述代码看起来也很直观易读,但是当字符串更长,待插入变量更多,则使用%来格式化字符串的可读性将急剧下降,如:

In [23]: first_name = "Eric"

In [24]: last_name = "Idle"

In [25]: age = 100

In [26]: profession = "comedian"

In [27]: affiliation = "Monty Python"

In [28]: "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
Out[28]: 'Hello, Eric Idle. You are 100. You are a comedian. You were a member of Monty Python.'

上述使用%格式化字符串不仅冗长,而且容易出错,因为这种方式并不够正确显示元组或者字典。

实际上,在Python官方文档中,对于使用%运算符格式化字符串这种方式的评价也是负面的:

The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as faipng to display tuples and dictionaries correctly).使用%格式化字符串会产生一系列异常,这些异常将引起一系列常见错误(如:无法正确显示元组和字典)。

Using the newerformatted string pterals, the str.format() interface, ortemplate strings may help avoid these errors.

使用更新的格式化字符串字面量(f-string:formatted string pterals),str.format()接口或者模板字符串(template strings)可以帮助避免这些错误。

Each of these alternatives provides their own trade-offs and benefits of simppcity, flexibipty, and/or extensibipty.

当然,上述三种可替代的格式化字符串方式也都在简洁、灵活和可扩展方面有所取舍。

二、str.format()格式化字符串

1. 如何使用

str.format()是对使用%实现格式化字符串的一种改进。这种方式使用的语法和普通函数调用相差无几。

使用str.format(),字符串中待替换的域使用{}表示:

In [29]: name = "Eric"

In [30]: age = 100

In [31]: "Hello, {}. You are {}.".format(name, age)
Out[31]: 'Hello, Eric. You are 100.'

也可以通过索引的方式指定format()中哪一个变量和值应该填入哪一个{},如:

In [32]: name = "Eric"

In [33]: age = 100

In [34]: "Hello, {1}. You are {0}.".format(age, name)
Out[34]: 'Hello, Eric. You are 100.'

除了索引,也可以通过在{}中指定名称的方式来实现类似上述功能,如:

In [36]: name = "Eric"

In [37]: age = 100

In [38]: "Hello, {name}. You are {age}.".format(age=age, name=name)
Out[38]: 'Hello, Eric. You are 100.'

基于上面的方式,当待格式化的信息都来自一个字典时,Python中还有如下骚操作:

In [39]: person = {'name': 'Eric', 'age': 100}

In [40]: "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
Out[40]: 'Hello, Eric. You are 100.'

更骚的是,上面的骚操作还能利用字典拆包**进一步简化:

In [41]: person = {'name': 'Eric', 'age': 100}

In [42]: "Hello, {name}. You are {age}.".format(**person)
Out[42]: 'Hello, Eric. You are 100.'

2. 缺点概述

相较于%运算符方式,使用str.format()已经使得格式化字符串语法更加可读,但是当变量增多时,这种方式写出的程序也会显得很冗长:

In [43]: first_name = "Eric"

In [44]: last_name = "Idle"

In [45]: age = 74

In [46]: profession = "comedian"

In [47]: affiliation = "Monty Python"

In [48]: 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.

三、f-string格式化字符串

在Python 3.6中f-string被引入(具体请见PEP 498),也被称作格式化字符串字面量(formatted string pterals)。

f-string是字符串字面量,且其以字母f开头,{}中包含变量或表达式,变量或表达式将在运行(runtime)时通过使用__format__协议被替换成具体的值。

1. 如何使用

简单的f-string格式化字符串如:

In [49]: name = "Eric"

In [50]: age = 100

In [51]: f"Hello, {name}. You are {age}."
Out[51]: 'Hello, Eric. You are 100.'

如前所述,{}中除接受变量外,还接受表达式,如:

In [52]: f"{2 * 37}"
Out[52]: '74'

f-string更强大的地方在于,{}中接受函数调用:

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

In [54]: name = "Eric Idle"

In [55]: f"{to_lowercase(name)} is funny."
Out[55]: 'eric idle is funny.'

甚至,你可以对创建于类的对象使用f-string,如:

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!"


def main():
  new_comedian = Comedian("Eric", "Idle", "74")
  print(f"{new_comedian}")


if __name__ == '__main__':
  main()

上述代码的输出为:

Eric Idle is 74.

热门栏目