zoukankan      html  css  js  c++  java
  • 字符串处理关键字str 和 repr

    字符串处理关键字str 和 repr

    >>> 10000l

    10000L

    >>> 100000L

    100000L

    >>> print 10000L

    10000

    >>> print "hello world"

    hello world

    可以看到,长整型数10000L 被转换成了数字10000,而且在显示给用户的时候也如此,但是当你想知道一个变量的值时,上面的输出可能会有些问题出现;

    这时,如果你明确你要的内容,你使用两个关键字str 和 repr

    repr 会让你输出的明确是一个字符串,他不会有所改变;

    而str 会根据一些内部的判断,将你的输入数据做一些改变;

    就如下的数据:

    >>> print str("10000l")

    10000l

    >>> print str(10000l)

    10000

    >>> print str("hello world")

    hello world

    >>> print repr(1000l)

    1000L

    repr(x) 也可以写作`x`实现(注意、`是反引号,而不是单引号)。如果 希望打印一个包含数字的句子,那么反引号就很有用了。比如:

    >>> temp = 42

    >>> print "the temp =" + temp

    Traceback (most recent call last):

      File "<stdin>", line 1, in <module>

    TypeError: cannot concatenate 'str' and 'int' objects

    >>> print "the temp =" + `temp`

    the temp =42

    >>> print "the temp =" + repr(temp)

    the temp =42

    第一个print 语句并不是不能工作,而是因为不能将字符串和数字进行相加。而第二个可以正常工作,因为我们已经通过反引号将temp的值转换为字符串“42”了。(反引号在3版本中,已经作废,就是让你在看到老的程序时,知道这方面的内容)。

    简而言,str、repr是将python值转换为字符串的方法。

    函数str让字符串更易于阅读,而repr则把结果字符串转换为合法的python表达式。

  • 相关阅读:
    sublime tex创建可服用的片段
    php unset
    使用VS.NET来制作安装程序
    手机暗码大全.(挺好玩的..)
    【转】双目运算符 "??"
    linuxcp命令
    ios——在iPhone程序中打开其它程序
    IOS地图项目01网络编程很难么???
    C# BitArray 实例
    Windows Phone 8使用初体验
  • 原文地址:https://www.cnblogs.com/aiyq195/p/6497775.html
Copyright © 2011-2022 走看看