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

  • 相关阅读:
    python正则表达式
    正则表达式
    python装饰器
    冒泡排序算法与递归
    C语言typedef定义结构体数组,下面这段代码是什么意思?
    链表实现的简单循环队列
    数组实现的简单循环队列
    悬空指针
    NULL代表什么
    Unity学习——Network Transform和 Network Transform Child组件
  • 原文地址:https://www.cnblogs.com/juanbai/p/6508901.html
Copyright © 2011-2022 走看看