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表达
式。

posted @ 2014-05-10 13:28  透明的空气  阅读(343)  评论(0编辑  收藏  举报