Python -- 值转换为字符串的两种机制

时间:2024-04-30 13:59:32

可以通过以下两个函数来使用这两种机制:一是通过str函数,它会把值转换为合理形式的字符串,以便用户可以理解;而repr会创建一个字符串,它以合法的Python表达式的形式来表示值。下面是一些例子:

>>> print repr("Hello, world!")
'Hello, world!'
>>> print repr(10000L)
10000L
>>> print str("Hello, world!")
Hello, world!
>>> print str(10000L)
10000

repr(x)的功能也可以用`x`实现(注意,`是反引号,而不是单引号,在键盘tab上面,数字1前面)。如果希望打印一个包含数字的句子,那么反引号就很有用了。

>>> temp = 42
>>> print "the temperature is " + temp
Traceback (most recent call last):
File "<pyshell#61>", line 1, in?
print "the temperature is " + temp
TypeError: cannot add type "int" to string
>>> print "the temperature is " + `temp`
the temperature is 42

注意,在Python3.0 中,已经不再使用反引号了。因此,即使在旧的代码中看到了反引号,你也应该坚持使用repr。

简而言之, str、repr和反引号是将Python值转换为字符串的3种方法。函数str让字符串更易于阅读,而repr(和反引号)则把结果字符串转换为合法的Python表达式。