您现在的位置是:亿华云 > IT科技类资讯

Python 的 f-strings 作用远超你的预期

亿华云2025-10-03 02:20:30【IT科技类资讯】2人已围观

简介学过 Python 的朋友应该都知道 f-strings 是用来非常方便的格式化输出的,觉得它的使用方法无外乎就是 print(fvalue = { value },其实,f-strings 远超你的

 学过 Python 的用远预期朋友应该都知道 f-strings 是用来非常方便的格式化输出的,觉得它的用远预期使用方法无外乎就是 print(fvalue = { 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、用远预期字符串对齐,so easy! 

>>> x = test    >>> f{ x:>10}   # 右对齐,左边补空格          test    >>> f{ x:*<10}  # 左对齐,亿华云计算右边补*    test

很赞哦!(81383)