Python 中的 %i 和 %d 有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17680256/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:53:14  来源:igfitidea点击:

What is the difference between %i and %d in Python?

pythonpython-2.7integerstring-formattingnumber-formatting

提问by

OK I was looking into number formatting and I found that you could use %dor %ito format an integer. For example:

好的,我正在研究数字格式,我发现您可以使用%d%i来格式化整数。例如:

number = 8
print "your number is %i." % number

or

或者

number = 8
print "your number is %d." % number

But what is the difference? I mean i found something but it was total jibberish. Anyone speak Mild-Code or English here?

但有什么区别呢?我的意思是我找到了一些东西,但它完全是胡言乱语。这里有人说轻度代码或英语吗?

采纳答案by Martijn Pieters

Python copied the C formatting instructions.

Python 复制了 C 格式化指令。

For output, %iand %dare the exact same thing, both in Python and in C.

对于output%iand%d是完全相同的东西,在 Python 和 C 中都是如此。

The difference lies in what these do when you use them to parse input, in C by using the scanf()function. See Difference between format specifiers %i and %d in printf.

不同之处在于当您使用它们在 C 中通过使用函数解析input时它们的scanf()作用。请参阅printf 中格式说明符 %i 和 %d 之间的区别

Python doesn't have a scanfequivalent, but the Python string formatting operations retained the two options to remain compatible with C.

Python 没有scanf等效项,但 Python 字符串格式化操作保留了两个选项以保持与 C 兼容。

The new str.format()and format()format specification mini-languagedropped support for iand stuck with donly.

新的str.format()format()格式规范的迷你语言放弃了支持id只坚持使用。

回答by Sven

There isn't any, see the Python String Formatting Manual: http://docs.python.org/2/library/stdtypes.html#string-formatting

没有,请参阅 Python 字符串格式手册:http: //docs.python.org/2/library/stdtypes.html#string-formatting

回答by tenstar

No difference.

没有不同。

And here's the proof.

这就是证据。

The reason why there are two is that, %i is just an alternative to %d ,if you want to look at it at a high level (from python point of view).

有两个的原因是, %i 只是 %d 的替代品,如果你想从更高的层次上看它(从python的角度来看)。

Here's what python.org has to say about %i: Signed integer decimal.

以下是 python.org 对 %i 的评论: Signed integer decimal.

And %d: Signed integer decimal.

还有 %d: Signed integer decimal.

%d stands for decimal and %i for integer.

%d 代表十进制,%i 代表整数。

but both are same, you can use both.

但两者都是相同的,您可以同时使用两者。