Python 中 f-Strings 的作用
作者:somenzz 时间:2022-12-04 11:44:55
学过 Python
的朋友应该都知道 f-strings
是用来非常方便的格式化输出的,觉得它的使用方法无外乎就是 print(f'value = { value }'
,其实,f-strings
远超你的预期,今天来梳理一下它还能做那些很酷的事情。
1、变量名
str_value = "hello,python coders"
print(f"{ str_value = }")
# str_value = 'hello,python coders'
2、直接改变输出结果
num_value = 123
print(f"{num_value % 2 = }")
# num_value % 2 = 1
3、直接格式化日期
import datetime
today = datetime.date.today()
print(f"{today: %Y%m%d}")
# 20211019
print(f"{today =: %Y%m%d}")
# today = 20211019
4、2/8/16 进制输出真的太简单
>>> a = 42
>>> f"{a:b}" # 2进制
'101010'
>>> f"{a:o}" # 8进制
'52'
>>> f"{a:x}" # 16进制,小写字母
'2a'
>>> f"{a:X}" # 16进制,大写字母
'2A'
>>> f"{a:c}" # ascii 码
'*'
5、格式化浮点数
>>> num_value = 123.456
>>> f'{num_value = :.2f}' #保留 2 位小数
'num_value = 123.46'
>>> nested_format = ".2f" #可以作为变量
>>> print(f'{num_value:{nested_format}}')
123.46
6、字符串对齐
>>> x = 'test'
>>> f'{x:>10}' # 右对齐,左边补空格
' test'
>>> f'{x:*<10}' # 左对齐,右边补*
'test******'
>>> f'{x:=^10}' # 居中,左右补=
'===test==='
>>> x, n = 'test', 10
>>> f'{x:~^{n}}' # 可以传入变量 n
'~~~test~~~'
>>>
7、使用 !s,!r
>>> x = '中'
>>> f"{x!s}" # 相当于 str(x)
'中'
>>> f"{x!r}" # 相当于 repr(x)
"'中'"
8、自定义格式
class MyClass:
def __format__(self, format_spec) -> str:
print(f'MyClass __format__ called with {format_spec=!r}')
return "MyClass()"
print(f'{MyClass():bala bala %%MYFORMAT%%}')
输出如下:
MyClass __format__ called with format_spec='bala bala %%MYFORMAT%%'
MyClass()
最后:
Python
的 f-string
非常灵活优雅,同时还是效率最高的字符串拼接方式:
以后关于字符串的格式化,就 f-string
了。
来源:https://developer.51cto.com/art/202110/686276.htm
标签:Python,f-Strings


猜你喜欢
Python字典删除键值对和元素的四种方法(小结)
2021-06-12 22:58:24
python实现超级玛丽游戏
2023-10-02 20:19:28

巧用Dreamweaver MX设计导航栏特效
2009-07-10 13:17:00

Python基于动态规划算法解决01背包问题实例
2021-01-10 21:22:26

通俗的讲解深度学习中CUDA,cudatookit,cudnn和pytorch的关系
2023-05-02 05:07:34

SQLServer 中的死锁说明
2024-01-25 16:10:27

python+OpenCV实现车牌号码识别
2023-04-13 14:50:20

python 上下文管理器使用方法小结
2021-08-11 07:27:30
OL IE Bug
2009-09-09 16:25:00
高性能JavaScript模板引擎实现原理详解
2024-04-18 09:37:11

TensorFlow中关于tf.app.flags命令行参数解析模块
2021-10-17 03:40:40

python selenium登录豆瓣网过程解析
2021-12-15 09:52:49
pandas实现导出数据的四种方式
2023-01-03 14:57:57
Python实现采集网站ip代理并检测是否可用
2021-01-10 09:10:53

python配置虚拟环境步骤
2023-10-22 09:34:51

Bootstrap DateTime Picker日历控件简单应用
2024-05-11 09:34:14

SQL语句中的一些特殊参数如何用变量来代替
2008-03-14 07:44:00
微信小程序访问mysql数据库流程详解
2024-01-23 10:34:43

PHP实现无限极分类的两种方式示例【递归和引用方式】
2023-11-15 18:26:33
Python完全识别验证码自动登录实例详解
2023-12-17 03:58:14