Python 2.7:%d、%s 和 float()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15215242/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python 2.7: %d, %s, and float()
提问by user2134093
I am attempting to teach myself a little coding through the "learn python the hard way" book and am struggling with %d / %s / %r when tying to display a floating point number. How do you properly pass a floating point number with a format character? First I tried %d but that made my answers display as integers.... I had some success with %r, but I was under the assumption that was usually reserved for debugging? I figured out for division in python 2.x you have to manually float the denominator for it to properly work for some reason.
我正在尝试通过“以艰难的方式学习 Python”一书自学一些编码,并且在绑定显示浮点数时遇到了 %d / %s / %r 问题。如何正确传递带有格式字符的浮点数?首先我尝试了 %d 但这使我的答案显示为整数....我在 %r 上取得了一些成功,但我假设通常保留用于调试?我发现在 python 2.x 中的除法你必须手动浮动分母,因为某种原因它才能正常工作。
Example code:
示例代码:
def divide (a, b):
print "WE DIVIDING %r and %r NOW" % (a, b)
return a / float(b)
print "Input first number:"
first = float(raw_input("> "))
print "OK, now input second number:"
second = float(raw_input("> "))
ans = divide(first, second)
print "DONE: %r DIVIDED BY %r EQUALS %r, SWEET MATH BRO!" % (first, second, ans)
采纳答案by p0lAris
Try the following:
请尝试以下操作:
print "First is: %f" % (first)
print "Second is: %f" % (second)
I am unsure what answer is. But apart from that, this will be:
我不确定答案是什么。但除此之外,这将是:
print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)
There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:
格式字符串说明符有很多文本。你可以谷歌它并获得说明符列表。我忘了注意一件事:
If you try this:
如果你试试这个:
print "First is: %s" % (first)
It converts the float value in first to a string. So that would work as well.
它首先将浮点值转换为字符串。所以这也能奏效。
回答by Mark Tolonen
See String Formatting Operations:
请参阅字符串格式化操作:
%dis the format code for an integer. %fis the format code for a float.
%d是整数的格式代码。 %f是浮点数的格式代码。
%sprints the str()of an object (What you see when you print(object)).
%s打印str()对象的 的(您看到的内容print(object))。
%rprints the repr()of an object (What you see when you print(repr(object)).
%r打印repr()对象的print(repr(object)).
For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:
对于浮点 %s,%r 和 %f 都显示相同的值,但并非所有对象都是这种情况。格式说明符的其他字段的工作方式也不同:
>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
1.12

