当前位置: 首页 > 科技观察

Python的f-strings的功能远超你的意料_0

时间:2023-03-17 11:52:15 科技观察

学过Python的朋友应该都知道,f-strings用来格式化输出非常方便。={value}',其实f-strings远远超出你的想象,今天就来梳理一下它能干出哪些酷炫的事情。1.懒得再打变量名str_value="hello,pythoncoders"print(f"{str_value=}")#str_value='hello,pythoncoders'2.直接改输出结果num_value=123print(f"{num_value%2=}")#num_value%2=13,直接格式化日期importdatetimetoday=datetime.date.today()print(f"{today:%Y%m%d}")#20211019print(f"{today=:%Y%m%d}")#today=202110194,2/8/16十六进制输出真的太简单了>>>a=42>>>f"{a:b}"#2进入System'101010'>>>f"{a:o}"#八进制'52'>>>f"{a:x}"#十六进制,小写字母'2a'>>>f"{a:X}"#十六进制,大写字母'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.466,字符串对齐,所以简单的!>>>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.自定义格式类MyClass:def__format__(self,format_spec)->str:print(f'MyClass__format__calledwith{format_spec=!r}')return"MyClass()"print(f'{MyClass():balabala%%MYFORMAT%%}')输出如下:MyClass__format__calledwithformat_spec='balabala%%MYFORMAT%%'MyClass()最终的Pythonf-string非常灵活和优雅,同时也是最高效的字符串拼接方式:以后关于字符串的格式化,都会使用f-string。如果您觉得自己有所收获,请点赞、观看、关注。感谢您的支持!