推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
hush
V2EX  ›  Python

关于 str 的类型转换

  •  
  •   hush · Jan 29, 2015 · 4514 views
    This topic created in 4300 days ago, the information mentioned may be changed or developed.
    问题:判断来两个变量dataA,dataB是否为str类型,一个是则输出'Ture'
    方法1:if dataA==type(dataA) or dataB==type(dataB):
    print ’True‘
    方法2:if dataA==str(dataA) or dataB==str(dataB):
    print ’True‘
    现在的问题:第二个方法中的str(dataA)的执行是否会有错误,即Python中强制转换是否可行?如果不行能否给我一个反例
    12 replies  •  2015-01-29 18:44:57 +08:00
    ruoyu0088
    ruoyu0088
    Jan 29, 2015
    1
    你的程序和你的问题对不上啊。
    raquelken
    raquelken
    Jan 29, 2015
    2
    python里面判断类型的方法是 isinstance
    broono
    broono
    Jan 29, 2015
    3
    不应该是这样吗:
    if isinstance(dataA,'str') and isinstance(dataB,'str'):
    print 'True'
    hush
    hush
    OP
    Jan 29, 2015
    4
    @ruoyu0088 就是现在用的方法不是考虑不全面
    hush
    hush
    OP
    Jan 29, 2015
    5
    上面的两个方法都能运行得到效果,但就第二种不全面
    hahastudio
    hahastudio
    Jan 29, 2015
    6
    你的问题大概是你觉得找到了

    >>> s = "a"
    >>> isinstance(s, str)
    True
    >>> type(s) == str
    True
    >>> class bar(str):
    def __init__(self):
    pass

    >>> b = bar()
    >>> type(b) == str
    False
    >>> isinstance(b, str)
    True

    然后你要知道 x.__str__() <==> str(x) 就可以了
    str(x) 就相当于其他语言的 x.ToString()
    hush
    hush
    OP
    Jan 29, 2015
    7
    @hahastudio 你的意思是 str(X)使用这个是不会有错的吗?
    buru
    buru
    PRO
    Jan 29, 2015
    8
    肯定不会有错误的 ,每个类型都有__str__方法
    @hush
    hush
    hush
    OP
    Jan 29, 2015 via Android
    9
    @buru 嗯,好的谢谢了
    Valyrian
    Valyrian
    Jan 29, 2015
    10
    方法一是错的,左边是str右边是type
    方法二也是错的,如果dataA类型的__eq__()方法允许和str相等的话

    建议isinstance(dataA, str)或者type(dataA) == type("")
    Valyrian
    Valyrian
    Jan 29, 2015
    11
    补充一句,如果dataA是一个str的子类,isinstance()会true,type(dataA) == type("")会false
    所以你如果想要dataA是严格的str就用type(dataA) == type(""),如果不在乎是子类就用isinstance()
    zhicheng
    zhicheng
    Jan 29, 2015
    12
    >>> isinstance('abc', str)
    True
    >>> isinstance(u'abc', str)
    False
    >>> isinstance('abc', unicode)
    False
    >>> isinstance(u'abc', unicode)
    True
    >>> isinstance('abc', basestring)
    True
    >>> isinstance(u'abc', basestring)
    True
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1871 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 08:59 · PVG 16:59 · LAX 00:59 · JFK 03:59
    ♥ Do have faith in what you're doing.