python中,str和repr的区别

it2022-05-09  26

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

Java代码  >>> print repr("hello, world!")  'hello, world!'  >>> print repr(1000L)  1000L  >>> print str("hello, wolrd!")  hello, wolrd!  >>> print str(1000L)  1000  

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

Java代码  >>> temp = 42L  >>> print "The temperature is " + `temp`  The temperature is 42L  >>>  

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

转载于:https://www.cnblogs.com/yongpan666/p/3720385.html


最新回复(0)