python最佳实践,格式化输出字符串的四种方案对比
发布于 作者:苏南大叔 来源:程序如此灵动~
都21世纪了,该不会还不知道:python
格式化输出字符串有好多种方案吧?本文中苏南大叔就来总结一下格式化输出字符串的四种方案。(从短视频里面学习的文案开头...)
大家好,这里是苏南大叔的“程序如此灵动”博客,记录苏南大叔和计算机代码的故事。本文测试环境:win10
,python@3.12.0
。
方案一,str()
import numpy as np
S = np.array([[1,2,3],[2,3,4]])
print('目标形状:' + str(S.shape))
这个地方,唯一要说明的就是:tuple
类型转字符串,使用的是str()
函数。输出:
目标形状:(2, 3)
方案二,f"{}"
import numpy as np
S = np.array([[1,2,3],[2,3,4]])
print(f"目标形状:{S.shape}")
print(f'目标形状:{S.shape}')
这里使用单引号和双引号没有啥区别,但是前面加了一个f
字符,所以后面大括号里面可以直接写表达式。输出:
目标形状:(2, 3)
目标形状:(2, 3)
参考文章:
方案三,"{}".format()
import numpy as np
S = np.array([[1,2,3],[2,3,4]])
print('目标形状:{}'.format(S.shape))
输出:
目标形状:(2, 3)
参考文章:
- https://newsn.net/say/python-format-star.html
- https://newsn.net/say/python-format-class.html
- https://newsn.net/say/python-format-number.html
方案四,'%s'%str()
import numpy as np
S = np.array([[1,2,3],[2,3,4]])
print('目标形状:%s'% str(S.shape) )
print('目标形状:%s'%(str(S.shape)))
这个地方值得说明的是:%(,)
,可以格式化多个目标数据。输出:
目标形状:(2, 3)
目标形状:(2, 3)
参考文章:
结语
其实本文的文章代码挺简单的,就是个总结类的文章而已。不过,是不是也很惊讶呢?居然真的有这么多写法...更多python
相关文章,请点击:


