Cannot Figure out how String Substitution works in Python 3.x(无法弄清楚字符串替换在 Python 3.x 中是如何工作的)
问题描述
在 python 2.x 中,你可以这样做:
In python 2.x you were allowed to do something like this:
>>> print '%.2f' % 315.15321531321
315.15
但是,我无法让它在 python 3.x 上工作,我尝试了不同的方法,例如
However, i cannot get it to work for python 3.x, I tried different things, such as
>>> print ('%.2f') % 315.15321531321
%.2f
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'float'
>>> print ("my number %") % 315.15321531321
my number %
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for %: 'NoneType' and 'float'
然后,我阅读了 .format() 方法,但我也无法让它工作
Then, I read about the .format() method, but I cannot get it to work either
>>> "my number {.2f}".format(315.15321531321)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'float' object has no attribute '2f'
>>> print ("my number {}").format(315.15321531321)
my number {}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'format'
我很乐意收到任何提示和建议!
I would be happy about any tips and suggestions!
推荐答案
尝试发送带有格式的整个字符串进行打印.
Try sending the entire string with formatting to print.
print ('%.2f' % 6.42340)
适用于 Python 3.2
Works with Python 3.2
此外,该格式通过为所提供的 agruments 提供索引来工作
In addition, the format works by providing an index to the provided agruments
print( "hello{0:.3f}".format( 3.43234 ))
注意格式标志前面的0".
Notice the '0' in front of the format flags.
这篇关于无法弄清楚字符串替换在 Python 3.x 中是如何工作的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法弄清楚字符串替换在 Python 3.x 中是如何工作的


- 检查具有纬度和经度的地理点是否在 shapefile 中 2022-01-01
- 我如何透明地重定向一个Python导入? 2022-01-01
- 使用公司代理使Python3.x Slack(松弛客户端) 2022-01-01
- ";find_element_by_name(';name';)";和&QOOT;FIND_ELEMENT(BY NAME,';NAME';)";之间有什么区别? 2022-01-01
- 我如何卸载 PyTorch? 2022-01-01
- 计算测试数量的Python单元测试 2022-01-01
- YouTube API v3 返回截断的观看记录 2022-01-01
- 如何使用PYSPARK从Spark获得批次行 2022-01-01
- 使用 Cython 将 Python 链接到共享库 2022-01-01
- CTR 中的 AES 如何用于 Python 和 PyCrypto? 2022-01-01