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 中是如何工作的
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
