为什么我会在 Python 字符串格式中使用 %r 以外的任何东西? [英] Why would I ever use anything else than %r in Python string formatting?

查看:29
本文介绍了为什么我会在 Python 字符串格式中使用 %r 以外的任何东西?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

print('int: %i.Float: %f.String: %s' % (54, 34.434, 'some text'))

但是,这也可以这样做:

print('int: %r. Float: %r. String: %r' % (54, 34.434, 'some text'))

以及使用 %s:

print('int: %s. Float: %s. String: %s' % (54, 34.434, 'some text'))

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

添加了带有 %s 的示例

解决方案

对于浮点数,reprstr 的值可以不同:

<预><代码>>>>数量 = .2 + .1>>>'浮动:%f.Repr: %r Str: %s' % (num, num, num)'浮点数:0.300000.代表:0.30000000000000004 Str:0.3'

对字符串使用 %r 将导致它周围有引号:

<预><代码>>>>'Repr:%r Str:%s' % ('foo','foo')代表:'foo' Str:foo"

您应该始终将 %f 用于浮点数,%d 用于整数.

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

解决方案

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.

这篇关于为什么我会在 Python 字符串格式中使用 %r 以外的任何东西?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆