气泡水 发表于 2021-12-17 13:42:06

Python 的 f-strings 作用

  学过 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、字符串对齐,so easy!

>>> 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七号 ,作者somenzz。转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责。如涉及作品内容、版权和其它问题,请在30日内与联系我们,我们会予以更改或删除相关文章,以保证您的权益!

页: [1]
查看完整版本: Python 的 f-strings 作用