本文介绍了str()和repr()是做什么的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 :
$ b

有趣的是,转换后的值是 repr(),而不是 str()。

 >>> str(math.pi)
'3.14159265359'
>>> repr(math.pi)
'3.141592653589793'

那么转换价值在这里呢?使它不那么容易理解?

解决方案

为了在中设置一个字符串,必须先创建一些东西的表示。 转换价值基本上是在谈论如何构建字符串表示。在python中,有两个相当自然的选择来得到字符串表示的东西... str 和 repr 。 str 通常更友好一些, repr 通常更精确。也许是寻找差异:

在 str.format ,!s 选择使用 str 来格式化对象,而!r 选择 repr 来格式化这个值。



可以很容易地看到字符串的区别( repr 为一个字符串将包括外部引号):

 >>> 'foo {}'。format('bar')
'foo bar'
>>> 'foo {!r}'。格式('bar')
foobar'



这两种方法之间的区别实际上取决于被格式化的对象。对于许多对象(例如那些不会覆盖 __ str __ 方法的对象),格式化输出将不会有任何区别。


According to the Python 2.7.12 documentation:

Interestingly, the converted value is the output of repr(), rather than str().

>>> str(math.pi)
'3.14159265359'
>>> repr(math.pi)
'3.141592653589793'

So what does "convert the value" mean here? Making it less human-readable?

解决方案

In order to format something in a string, a string representation of that something must first be created. "convert the value" is basically talking about how the string representation is to be constructed. In python, there are two fairly natural choices to get a string representation of something ... str and repr. str is generally a little more human friendly, repr is generally more precise. Perhaps the official documentation is the best place to go looking for the difference:

In str.format, !s chooses to use str to format the object whereas !r chooses repr to format the value.

The difference can easily be seen with strings (as repr for a string will include outer quotes).:

>>> 'foo {}'.format('bar')
'foo bar'
>>> 'foo {!r}'.format('bar')
"foo 'bar'"

What the difference between these two methods really depends critically on the objects being formatted. For many objects (e.g. those that don't override the __str__ method), there will be no difference in the formatted output.

这篇关于str()和repr()是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 11:53