登录
首页 >  文章 >  python教程

你会惊讶于 Python f-strings 的强大功能

来源:51CTO.COM

时间:2024-01-28 21:21:11 142浏览 收藏

各位小伙伴们,大家好呀!看看今天我又给各位带来了什么文章?本文标题《你会惊讶于 Python f-strings 的强大功能》,很明显是关于文章的文章哈哈哈,其中内容主要会涉及到等等,如果能帮到你,觉得很不错的话,欢迎各位多多点评和分享!

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:*>> 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 的强大功能》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于Python,字符串,f-strings的知识点!

声明:本文转载于:51CTO.COM 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>