「python|语言特性」为什么f-string是python中最舒适的字符串格式化方式
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
本文主要介绍python语言特性中关于字符串格式化的特性f-string的特点、具体用法和注意事项
文章目录
什么是f-string
f-string
是python3.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
的主要内容快快用起来吧
好书推荐
好课推荐
写文不易如果对你有帮助的话来一波点赞、收藏、关注吧~👇