「python|语言特性」为什么f-string是python中最舒适的字符串格式化方式

本文主要介绍python语言特性中关于字符串格式化的特性,f-string的特点、具体用法和注意事项

什么是f-string

  • f-stringpython3.6版本引入的语言特性。
  • f-string指的是带有一个f前缀的python字符串,我们在python字符串的文章中介绍了python的字符串可以是由单引号、双引号、三引号来标志。所以f-string可以是如下形式:
"""
以下三种都是f-string
"""
f'这是一个f-string'
f"这也是一个f-string"
f"""这还是一个f-string"""
  • f-string与字符串的内置方法str.format()一样,可以放入各种表达式,用一对花括号包裹表达式。重点在于,我们使用str.format()时还要将变量和表达式位置一一对应,f-string直接写入表达式,省去了一一对应的麻烦和可能带来的对应错误。如下:
"""
以下是str.format()和f-string的等价表示
"""
name = "Aki"
string_1 = "My name is {}".format(name)
string_2 = f"My name is {name}"
print(string_1 == string_2)
# 输出结果为: True

name = "Aki"
string_1 = "My name is {0}. Again, My name is {0}".format(name)
string_2 = f"My name is {name}. Again, My name is {name}"
print(string_1 == string_2)
# 输出结果为: True

  • f-string中表达式的值是在运行时(at Run time)根据python全局内置方法format()处理方式计算出来的。

f-string的各种用法

  • f-string本质是字符串,然后允许你在字符串中插入一些表达式(用花括号括起来),表达式包括单一的变量,运算式,变量的运算表达式,推导式等等。如下:
"""简单的变量"""
name = "Aki"
age = 18
basic_usage = f"My name is {name} and I'm {age}."

"""变量运算"""
age = 18
years = 3
content = f"I'm {age} this year. And {years} year(s) later, I would be {age + years} year-old."

"""直接放入推导式或者函数运算"""
string = "ABCD"
result = f"Convert string {string} as list: {list(string)}"
print(result)
# 输出结果: Convert string ABCD as list: ['A', 'B', 'C', 'D']

lst = ["A", "B", "C", "D"]
result = f"Convert list {lst} as string: {''.join(lst)}"
print(result)
# 输出结果: Convert list ['A', 'B', 'C', 'D'] as string: ABCD

numbers = list(range(1, 10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
result = f"All odd numbers: {[number for number in numbers if number % 2 == 0]}"
print(result)
# 输出结果: All odd numbers: [2, 4, 6, 8]

f-string的注意事项

  • f-string除了从可读性上更优之外,格式化字符串的效率是更高的,也就是说你的程度运行会更快。我们可以用如下代码测试运行速度:
import timeit

code_format_string_with_lazy_format = """
name = "Eric"
age = 74
'%s is %s.' % (name, age)
"""
code_format_string_with_str_format = """
name = "Eric"
age = 74
'{} is {}.'.format(name, age)
"""
code_format_string_with_f_string = """
name = "Eric"
age = 74
f'{name} is {age}.'
"""

test_times = 10000

print(f"""
Time cost of lazy format (%-format): {timeit.timeit(code_format_string_with_lazy_format, number=test_times)}
Time cost of str.format(): {timeit.timeit(code_format_string_with_str_format, number=test_times)}
Time cost of f-string: {timeit.timeit(code_format_string_with_f_string, number=test_times)}
""")
"""输出结果:
Time cost of lazy format (%-format): 0.002445499994792044
Time cost of str.format(): 0.004113400005735457
Time cost of f-string: 0.001851000008173287
"""
  • f-string本质是字符串,所以字符串内容中如果出现跟字符串外部的引号相同类型的引号,则需要进行转义。比如example = f'I\'m {18}'
  • 表达式中不能用转义符\
    • 所以转义字符都不能在表达式中出现,比如常用的换行符就不能写成content = f"{'\n'.join([1, 2, 3, 4])}",会抛出SyntaxError: f-string expression part cannot include a backslash的异常。
    • 但是花括号之外的地方可以用转义字符,比如content = f"first line\n{1234}\n{'third line'}\n{'last line'}"是符合语法规则的。
  • f-string的花括号中,不能使用花括号创建字典或者使用字典推导式,如下:
"""无法识别字典"""
content = f"不能使用花括号创建字典: {{2: 2 * 2, 3: '3'}}"
print(content)
# 输出结果: 不能使用花括号创建字典: {2: 2 * 2, 3: '3'}

"""无法识别字典推导式"""
numbers_from_1_to_10 = range(1, 11)
content = f"字典推导式(dict comprehension): {{number: number * 2 for number in number}}"
print(content)
# 输出结果: 字典推导式(dict comprehension): {number: number * 2 for number in number}

f-string中为表达式内容指定格式

这里补充说明如何在f-string中完成低位数高位补0,比如'1'变成'01'之类的格式化处理。

指定内容长度和填充内容

number = 123
f"{number:4}"
number = 123
print(f"默认长度不足的位置用空格填充: {number:4}")
# 输出结果: 默认长度不足的位置用空格填充:  123

print(f"默认长度不足的位置用0填充: {number:04}")
# 输出结果: 默认长度不足的位置用0填充: 0123

设置对齐方向

number = 123
print(f"长度为20, 默认是高位填充(所以默认是左对齐): {number:20}")
print(f"长度为20, 左对齐: {number:>20}")
print(f"长度为20, 右对齐: {number:<20}")
print(f"长度为20, 居中对齐: {number:^20}")
"""输出结果:
长度为20, 默认是高位填充(所以默认是左对齐):                  123
长度为20, 左对齐:                  123
长度为20, 右对齐: 123                 
长度为20, 居中对齐:         123  
"""

比如我们要模拟mysql的shell交互中的对齐格式, 则可以有如下写法:

"""
mysql数据: 
|name|age|job|
|Aki|18|programmer|
在shell中用select语句查询出来可以是如上形式也可以用`\G`参数显示成如下形式
************************ 1. row ***************************
           name: Aki
            age: 18
            job: programmer
****************************************************************
"""
record = {
    "name": "Aki",
    "age": 18,
    "job": "programmer",
}
print('*' * 64)
print("\n".join([f"{key: >20}: {value}" for key, value in record.items()]))
print('*' * 64)
"""输出结果:
****************************************************************
                name: Aki
                 age: 18
                 job: programmer
****************************************************************
"""

""""默认是空格填充, 我们也可以指定其他字符来填充前面的空格"""
record = {
    "name": "Aki",
    "age": 18,
    "job": "programmer",
}
print('*' * 64)
print("\n".join([f"{key:#>20}: {value}" for key, value in record.items()]))
print('*' * 64)
"""输出结果:
****************************************************************
################name: Aki
#################age: 18
#################job: programmer
****************************************************************
"""

以上就是f-string的主要内容,快快用起来吧!

好书推荐:

好课推荐:

写文不易,如果对你有帮助的话,来一波点赞、收藏、关注吧~👇

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明仔的阳光午后

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值