文章目录
- 1. 用法示例
- 2. 语法解释
- 3.f-string结合%f format控制小数点位数
- 4. python的format格式化补0
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/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/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“的用处
发布评论