千家信息网

Python中f-Strings有什么用

发表于:2025-11-06 作者:千家信息网编辑
千家信息网最后更新 2025年11月06日,这篇文章主要介绍了Python中f-Strings有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。1、变量名str_value
千家信息网最后更新 2025年11月06日Python中f-Strings有什么用

这篇文章主要介绍了Python中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()

最后:

Pythonf-string 非常灵活优雅,同时还是效率最高的字符串拼接方式:

以后关于字符串的格式化,就 f-string 了。

感谢你能够认真阅读完这篇文章,希望小编分享的"Python中f-Strings有什么用"这篇文章对大家有帮助,同时也希望大家多多支持,关注行业资讯频道,更多相关知识等着你来学习!

0