str和repr区别 分类: python学习 2014-06-23 10:05 205人阅读 评论(0) 收藏

str函数,它会把值转换为合理形式的字符串,以便用户可以理解。 


repr会创建一个字符串,它以合法的Python表达式的形式来表示值。 

例如: 


  • >>> print repr("hello, world!")  
  • 'hello, world!'  
  • >>> print repr(1000L)  
  • 1000L  
  • >>> print str("hello, wolrd!")  
  • hello, wolrd!  
  • >>> print str(1000L)  
  • 1000  


    repr(x)的功能也可以用`x`实现(注意, `是反引号,而不是单引号),例如: 


  • >>> temp = 42L  
  • >>> print "The temperature is " + `temp`  
  • The temperature is 42L  
  • >>>  


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


    源地址:http://greybeard.iteye.com/blog/1283897

  • posted @ 2014-06-23 10:05  冰菓折木  阅读(142)  评论(0编辑  收藏  举报