为什么我会在Python字符串格式中使用%r以外的任何东西?

kra*_*r65 5 python string-formatting

我偶尔会使用Python字符串格式.这可以这样做:

print('int: %i. Float: %f. String: %s' % (54, 34.434, 'some text'))
Run Code Online (Sandbox Code Playgroud)

但是,这也可以这样做:

print('int: %r. Float: %r. String: %r' % (54, 34.434, 'some text'))
Run Code Online (Sandbox Code Playgroud)

以及使用%s:

print('int: %s. Float: %s. String: %s' % (54, 34.434, 'some text'))
Run Code Online (Sandbox Code Playgroud)

因此,我的问题是:为什么我会使用%r或%s以外的任何东西?其他选项(%i,%f和%s)对我来说似乎毫无用处,所以我只是想知道为什么每个人都会使用它们?

[edit]在%s中添加了示例

Ash*_*ary 8

对于花车,价值reprstr可能会有所不同:

>>> num = .2 + .1
>>> 'Float: %f. Repr: %r Str: %s' % (num, num, num)
'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3'
Run Code Online (Sandbox Code Playgroud)

使用%r字符串将导致周围的引号:

>>> 'Repr:%r Str:%s' % ('foo','foo')
"Repr:'foo' Str:foo"
Run Code Online (Sandbox Code Playgroud)

你应该总是使用%f浮点数和%d整数.