这篇文章主要介绍了Python中f-Strings有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
str_value = "hello,python coders"
print(f"{ str_value = }")
# str_value = 'hello,python coders'
num_value = 123
print(f"{num_value % 2 = }")
# num_value % 2 = 1
import datetime
today = datetime.date.today()
print(f"{today: %Y%m%d}")
# 20211019
print(f"{today =: %Y%m%d}")
# today = 20211019
>>> 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 码
'*'
>>> num_value = 123.456
>>> f'{num_value = :.2f}' #保留 2 位小数
'num_value = 123.46'
>>> nested_format = ".2f" #可以作为变量
>>> print(f'{num_value:{nested_format}}')
123.46
>>> x = 'test'
>>> f'{x:>10}' # 右对齐,左边补空格
' test'
>>> f'{x:*<10}' # 左对齐,右边补*
'test******'
>>> f'{x:=^10}' # 居中,左右补=
'===test==='
>>> x, n = 'test', 10
>>> f'{x:~^{n}}' # 可以传入变量 n
'~~~test~~~'
>>>
>>> x = '中'
>>> f"{x!s}" # 相当于 str(x)
'中'
>>> f"{x!r}" # 相当于 repr(x)
"'中'"
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
非常灵活优雅,同时还是效率最高的字符串拼接方式:
以后关于字符串的格式化,就 f-string
了。
感谢你能够认真阅读完这篇文章,希望小编分享的“Python中f-Strings有什么用”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。