Python 中 f-Strings 的作用

作者:somenzz 时间:2022-12-04 11:44:55 

学过 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 了。

来源:https://developer.51cto.com/art/202110/686276.htm

标签:Python,f-Strings
0
投稿

猜你喜欢

  • 微信小程序页面缩放式侧滑效果的实现代码

    2023-09-02 05:21:45
  • 重新阅读《HTTP协议基础》

    2008-04-04 17:40:00
  • Flash在web客户端的潜在问题

    2009-05-20 12:11:00
  • ASP 支持中文的len(),left(),right()的函数代码

    2011-03-03 10:59:00
  • 你凭什么说你的网站用户体验好

    2011-03-31 17:08:00
  • python生成九宫格图片

    2022-09-09 04:46:34
  • 10点优化sql数据库技巧

    2008-06-09 15:00:00
  • 图片预加载效果的实现

    2008-06-16 12:08:00
  • python对象销毁实例(垃圾回收)

    2022-07-29 06:22:14
  • python使用selenium打开chrome浏览器时带用户登录信息实现过程详解

    2023-07-19 05:00:37
  • FrontPage XP设计教程2——网页的编辑

    2008-10-11 12:16:00
  • Django MEDIA的配置及用法详解

    2022-12-12 01:35:41
  • { hide_text } CSS文字隐藏总结报告

    2010-06-13 17:19:00
  • Python实现远程调用MetaSploit的方法

    2022-07-17 05:40:31
  • 手机版远程网站文件删除ASP程序

    2009-02-24 16:23:00
  • 了解ASP的基本语法和变量

    2008-01-16 13:03:00
  • oracle 数据库连接分析

    2009-07-28 10:42:00
  • Go语言从单体服务到微服务设计方案详解

    2023-09-02 02:45:57
  • python3调用R的示例代码

    2021-05-01 21:53:59
  • 互联网一家之言(一):叫用户为你买单

    2009-06-09 11:32:00
  • asp之家 网络编程 m.aspxhome.com