简体   繁体   English

如何在Python 2.7中正确使用字符串格式?

[英]How to properly use string formatting in Python 2.7?

Ok, please bear with me, I'm completely new to this. 好吧,请多多包涵,我对此完全陌生。 This is for school, and the exact syntax isn't important here for my assignment, but for my own personal knowledge I want to know a little more about string formatting. 这是供学校使用的,确切的语法对于我的作业而言并不重要,但出于我个人的知识,我想对字符串格式有所了解。

whenever I use %f it defaults to 2 decimal places. 每当我使用%f时,它默认为2个小数位。 Is there a string format that I can use on a float that will show the float with the number of decimals it actually has? 我可以在浮点数上使用一种字符串格式来显示浮点数及其实际拥有的小数位数吗?

for instance my list contains 2.0, 2.01, 2.001, 2.0001 and I want to use a string format to print them as they look. 例如,我的列表包含2.0、2.01、2.001、2.0001,我想使用字符串格式按其外观进行打印。 Which format code would I use or how could I use %f properly if possible? 我将使用哪种格式的代码,或者在可能的情况下如何正确使用%f?

This is in Python 2.7 on Windows 7(if that matters). 这是Windows 7上的Python 2.7(如果重要)。

If you convert the float to a string, then when you print it, it will be displayed just as you wrote it. 如果将浮点数转换为字符串,则在打印时将按照编写时的显示方式进行显示。

>>> x = str(2.0)
>>> print(x)
2.0
>>> x = str(2.01)
>>> print(x)
2.01
>>> x = str(2.001)
>>> print(x)
2.001
>>> x = str(2.0001)
>>> print(x)
2.0001

(In fact, to be precise, in Python you're not actually converting the floating point object, but creating a string object that looks like it. But that's a bit outside of the scope of your question.) (实际上,确切地说,在Python中,您实际上并不是在转换浮点对象,而是创建了一个看起来像它的字符串对象。但这有点超出您的问题范围。)

UPDATE 更新

Someone posted a way to remove trailing zeros from floating point numbers using the Decimal class, here: Removing Trailing Zeros in Python 有人在这里发布了一种使用Decimal类从浮点数中删除尾随零的方法:在Python中删除尾随零

%g may be what you're looking for: %g可能是您要寻找的:

>>> "%g, %g, %g, %g" % (2.1, 2.01, 2.001, 2.0001)
'2.1, 2.01, 2.001, 2.0001'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM