大蟒蛇python教程共享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、字符串对齐

  >>> 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 非常灵活优雅,同时还是效率最高的字符串拼接方式:

Python 中 f-Strings 的作用

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

到此这篇关于python 中 f-strings 的作用的文章就介绍到这了,更多相关python f-strings 内容请搜索<计算机技术网(www.ctvol.com)!!>以前的文章或继续浏览下面的相关文章希望大家以后多多支持<计算机技术网(www.ctvol.com)!!>!

需要了解更多python教程分享Python 中 f-Strings 的作用,都可以关注python教程分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/pythontutorial/886871.html

(0)
上一篇 2021年10月22日
下一篇 2021年10月22日

精彩推荐