zoukankan      html  css  js  c++  java
  • Python -- 值转换为字符串的两种机制

    可以通过以下两个函数来使用这两种机制:一是通过str函数,它会把值转换为合理形式的字符串,以便用户可以理解;而repr会创建一个字符串,它以合法的Python表达式的形式来表示值。下面是一些例子:

    >>> print repr("Hello, world!")
    'Hello, world!'
    >>> print repr(10000L)
    10000L
    >>> print str("Hello, world!")
    Hello, world!
    >>> print str(10000L)
    10000

    repr(x)的功能也可以用`x`实现(注意,`是反引号,而不是单引号,在键盘tab上面,数字1前面)。如果希望打印一个包含数字的句子,那么反引号就很有用了。

    >>> temp = 42
    >>> print "the temperature is " + temp
    Traceback (most recent call last):
        File "<pyshell#61>", line 1, in?
            print "the temperature is " + temp
    TypeError: cannot add type "int" to string
    >>> print "the temperature is " + `temp`
    the temperature is 42

    注意,在Python3.0 中,已经不再使用反引号了。因此,即使在旧的代码中看到了反引号,你也应该坚持使用repr。

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

  • 相关阅读:
    Java之内存分析和String对象
    Android之MVC模式
    Java之排序总结
    Android之单元测试学习
    Silverlight 拖拽功能
    Silverlight 调用WebServices
    Silverlight IIS 7.5 部署SilverLight4网站以及问题解决
    Silverlight 控件和对话框 源自MSDN 参考
    Silverlight 动画示例
    Sliverlight 动画详细介绍
  • 原文地址:https://www.cnblogs.com/Joseph-AMI/p/4713003.html
Copyright © 2011-2022 走看看