python3中的格式化字符串 f-string

f-string

f-string 是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。与其他格式化方式相比,它们不仅更易读,更简洁。

在此之前,格式化字符串主要有以下两种方式

  • %-formatting
  • str.format()

 

%-formatting

例如:

 1 >>> name = 'tom'
 2 >>> 'hello %s' % name
 3 'hello tom'
 4 >>> PI = 3.141592653
 5 >>> "%0.2f" % PI
 6 '3.14'
 7 >>> name = "tom"
 8 >>> age = 2
 9 >>> action = "迅速"
10 >>> disposition = ""
11 >>> "猫的名字叫%s,今年%d岁了,抓老鼠非常%s,但是非常%s,白天总睡觉。"%(name, age, action, disposition)
12 '猫的名字叫tom,今年2岁了,抓老鼠非常迅速,但是非常懒,白天总睡觉。'

 

可以看到,在参数较少的时候,代码还比较简单,但是当参数多的时候,代码看上去就会比较复杂难懂。

 

str.format()

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

 1 >>> "{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
 2 'hello world'
 3 >>>
 4 >>> "{0} {1}".format("hello", "world")  # 设置指定位置
 5 'hello world'
 6 >>>
 7 >>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
 8 'world hello world'
 9 >>>
10 >>> "网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com")
11 '网站名:菜鸟教程, 地址 www.runoob.com'
12 >>>
13 >>> # 通过字典设置参数
14 >>> site = {"name": "菜鸟教程", "url": "www.runoob.com"}
15 >>> "网站名:{name}, 地址 {url}".format(**site)
16 '网站名:菜鸟教程, 地址 www.runoob.com'
17 >>>
18 >>> # 通过列表索引设置参数
19 >>> my_list = ['菜鸟教程', 'www.runoob.com']
20 >>> "网站名:{0[0]}, 地址 {0[1]}".format(my_list)  # "0" 是必须的
21 '网站名:菜鸟教程, 地址 www.runoob.com'

 

使用 str.format() 格式化代码比使用 %-formatting 更易读,但当处理多个参数和更长的字符串时,str.format()看起来仍然非常冗长。

 

f-string

f-string 格式化字符串以 f 开头,后面跟着字符串,字符串中的表达式用大括号 {} 包起来,它会将变量或表达式计算后的值替换进去,实例如下:

例如:

 1 >>> name = 'tom'
 2 >>> f'Hello {name}'  # 替换变量
 3 'Hello tom'
 4 >>>
 5 >>> f'{1+2}'         # 使用表达式
 6 '3'
 7 >>>
 8 >>> w = {'name': 'baidu', 'url': 'www.baidu.com'}
 9 >>> f'{w["name"]}: {w["url"]}'
10 'baidu: www.baidu.com'
11 >>>
12 >>> x = 1
13 >>> f'{x+1}'
14 '2'
15 >>> f'{x+1=}'
16 'x+1=2'

 

注意事项

当需要输出{}时,有两种方式

  1. 在{}使用 引号
  2. 使用{{}}
1 >>> cat_name = "tom"
2 >>> # 使用单引号
3 >>> f"{'{cat_name:' + cat_name + '}'}"
4 '{cat_name:tom}'
5 >>>
6 >>> # 使用{{}}
7 >>> f"{{cat_name:{cat_name}}}"
8 '{cat_name:tom}'

 

posted @ 2022-02-10 10:30  r1-12king  阅读(183)  评论(0编辑  收藏  举报