python中print语句添加“f“的用处

1. 用法示例

今天在学习pytorch的时候看到:
在这里插入图片描述
print语句中加入f就可以起到和format函数类似的作用。

tensor=torch.rand(3,4)
print(f"Shape of tensor:{tensor.shape}")
# 这条语句等效于
print("Shape of tensor:{}".format(tensor.shape))

在这里插入图片描述

2. 语法解释

参考python官方文档:
https://docs.python.org/3.6/whatsnew/3.6.html#pep-498-formatted-string-literals

这种字符常量表示方式是在python3.6之后引入的。

PEP 498(即Python Enhancement Proposals, Python增强提案或Python改进建议书),引入了一种新的字符串字面量:f-字符串,或格式化字符串字面量。格式化字符串字面值以’f’作为前缀,类似于str.format()所接受的格式字符串。它们包含用花括号括起来的替换字段。

更详细的介绍可以参考PEP 498的页面:https://www.python.org/dev/peps/pep-0498/

3.f-string结合%f format控制小数点位数

参考:Fixed digits after decimal with f-strings
在这里插入图片描述
或者回答中有人提到了:PEP 498 – Literal String Interpolation
在这里插入图片描述

4. python的format格式化补0

"{0:03d}".format(1)
> '001'

"{0:03d}".format(10)
>'010'

"{0:03d}".format(100)
>'100'

参考:

Python中,print函数加上f的作用是实现格式化字符串的功能。通过在字符串前加上f前缀,我们可以在字符串中使用花括号括起来的变量和表达式。这样,花括号里的变量和表达式会被转换成相应的字符串,并与前面的字符串一起输出。 例如,我们可以使用print(f"Hello, {name}!")来输出一个带有变量的字符串,其中name是一个变量。这样,name的值会被转换为字符串并与"Hello, "和"!"组合起来输出。 此外,我们还可以在花括号里使用格式化指令来进行更复杂的格式化操作。例如,{:02d}指令表示将一个整数格式化为两位数,不足两位时前面用0填充。这种格式化方式在处理时间、日期等需要特定格式的情况下非常有用。 总而言之,print(f)是Python中一种方便的字符串格式化方法,它允许我们在字符串中嵌入变量和表达式,并进行各种格式化操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [pythonprint语句添加“f“的用处](https://blog.csdn.net/Castlehe/article/details/116018385)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [pythonprint(f“ “)用法](https://blog.csdn.net/biedouwozi1/article/details/129468463)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吨吨不打野

解决了问题,觉得还行就给点

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值