str和repr区别

来源:互联网 发布:部落冲突狗升级数据 编辑:程序博客网 时间:2024/05/16 14:36

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

  • 0 0
    原创粉丝点击