关于 str 的类型转换

2015-01-29 14:03:27 +08:00
 hush
问题:判断来两个变量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中强制转换是否可行?如果不行能否给我一个反例
3213 次点击
所在节点    Python
12 条回复
ruoyu0088
2015-01-29 14:13:56 +08:00
你的程序和你的问题对不上啊。
raquelken
2015-01-29 14:17:23 +08:00
python里面判断类型的方法是 isinstance
broono
2015-01-29 14:24:13 +08:00
不应该是这样吗:
if isinstance(dataA,'str') and isinstance(dataB,'str'):
print 'True'
hush
2015-01-29 14:28:10 +08:00
@ruoyu0088 就是现在用的方法不是考虑不全面
hush
2015-01-29 14:30:10 +08:00
上面的两个方法都能运行得到效果,但就第二种不全面
hahastudio
2015-01-29 14:35:36 +08:00
你的问题大概是你觉得找到了

>>> 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
2015-01-29 14:46:16 +08:00
@hahastudio 你的意思是 str(X)使用这个是不会有错的吗?
buru
2015-01-29 14:59:07 +08:00
肯定不会有错误的 ,每个类型都有__str__方法
@hush
hush
2015-01-29 15:12:39 +08:00
@buru 嗯,好的谢谢了
Valyrian
2015-01-29 15:24:08 +08:00
方法一是错的,左边是str右边是type
方法二也是错的,如果dataA类型的__eq__()方法允许和str相等的话

建议isinstance(dataA, str)或者type(dataA) == type("")
Valyrian
2015-01-29 15:28:40 +08:00
补充一句,如果dataA是一个str的子类,isinstance()会true,type(dataA) == type("")会false
所以你如果想要dataA是严格的str就用type(dataA) == type(""),如果不在乎是子类就用isinstance()
zhicheng
2015-01-29 18:44:57 +08:00
>>> 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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/166477

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX