admin管理员组文章数量:1794759
python中print语句添加“f“的用处
文章目录
- 1. 用法示例
- 2. 语法解释
- 3.f-string结合%f format控制小数点位数
- 4. python的format格式化补0
今天在学习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官方文档: docs.python/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的页面:www.python/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 中str format 格式化数字补0方法
- stackoverflow:what does {:02d} mean in Python
- 7.1. string — Common string operations
版权声明:本文标题:python中print语句添加“f“的用处 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686584243a84495.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论