问题
I occasionally use Python string formatting. This can be done like so:
print('int: %i. Float: %f. String: %s' % (54, 34.434, 'some text'))
But, this can also be done like this:
print('int: %r. Float: %r. String: %r' % (54, 34.434, 'some text'))
As well as using %s:
print('int: %s. Float: %s. String: %s' % (54, 34.434, 'some text'))
My question is therefore: why would I ever use anything else than the %r or %s? The other options (%i, %f and %s) simply seem useless to me, so I'm just wondering why anybody would every use them?
[edit] Added the example with %s
回答1:
For floats, the value of repr
and str
can vary:
>>> num = .2 + .1
>>> 'Float: %f. Repr: %r Str: %s' % (num, num, num)
'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3'
Using %r
for strings will result in quotes around it:
>>> 'Repr:%r Str:%s' % ('foo','foo')
"Repr:'foo' Str:foo"
You should always use %f
for floats and %d
for integers.
回答2:
@AshwiniChaudhary answered your question concerning old string formatting, if you were to use new string formatting you would do the following:
>>> 'Float: {0:f}. Repr: {0!r} Str: {0!s}'.format(.2 + .1)
'Float: 0.300000. Repr: 0.30000000000000004 Str: 0.3'
Actually !s
is the default so you don't need it, the last format can simply be {0}
回答3:
With the others, you'll have much finer control over your results.
In the docs, they tell you exactly about the way you can fine-tune your results, such as
>>> "%x-%5x-%#5x-%05x-%#05x" % (12,12,12,12,12)
'c- c- 0xc-0000c-0x00c'
回答4:
You may use the fact that '%f' % variable
will raise an exception if the variable
is not numeric.
来源:https://stackoverflow.com/questions/17081815/why-would-i-ever-use-anything-else-than-r-in-python-string-formatting