读书人

python中str()跟repr()区别

发布时间: 2012-08-22 09:50:35 作者: rapoo

python中str()和repr()区别
str函数,它会把值转换为合理形式的字符串,以便用户可以理解。
repr函数,会创建一个字符串,它以合法的Python表达式的形式来表示值。
例如:
Java代码

  1. >>> print repr("hello, world!")
  2. 'hello, world!'
  3. >>> print repr(1000L)
  4. 1000L
  5. >>> print str("hello, wolrd!")
  6. hello, wolrd!
  7. >>> print str(1000L)
  8. 1000


repr(x)的功能也可以用`x`实现(注意, `是反引号,而不是单引号),例如:
Java代码
  1. >>> temp = 42L
  2. >>> print "The temperature is " + `temp`
  3. The temperature is 42L
  4. >>>

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

读书人网 >perl python

热点推荐