无法弄清楚如何在Python 3.x中的字符串替换工作 [英] Cannot Figure out how String Substitution works in Python 3.x

查看:347
本文介绍了无法弄清楚如何在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中的字符串替换工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆