Python 等同于contain的unicode字符串
尝试在python中使用contain时出错Python 等同于contain的unicode字符串,python,string,unicode,Python,String,Unicode,尝试在python中使用contain时出错 s = u"some utf8 words" k = u"one utf8 word" if s.contains(k): print "contains" 我如何达到同样的结果 使用普通ASCII字符串的示例 s = "haha i am going home" k = "haha" if s.contains(k): print "contains" 我使用的是Python2.7.xstr和unicode之间没有区别 p
s = u"some utf8 words"
k = u"one utf8 word"
if s.contains(k):
print "contains"
我如何达到同样的结果
使用普通ASCII字符串的示例
s = "haha i am going home"
k = "haha"
if s.contains(k):
print "contains"
我使用的是Python2.7.xstr和unicode之间没有区别
print u"ábc" in u"some ábc"
print "abc" in "some abc"
基本相同。ascii和utf8字符串相同:
if k in s:
print "contains"
>>> "strrtinggg".contains
AttributeError: 'str' object has no attribute 'contains'
ascii或uft8字符串上都没有contains()
:
if k in s:
print "contains"
>>> "strrtinggg".contains
AttributeError: 'str' object has no attribute 'contains'
您可以使用
查找或索引来代替包含的:
if k.find(s) > -1:
print "contains"
或
当然,
操作符中的是一个不错的选择,它更加优雅。字符串没有“contain”属性
s = "haha i am going home"
s_new = s.split(' ')
k = "haha"
if k in s_new:
print "contains"
我猜您希望在字符串中实现对字符串存在性的测试
u'…'
对象不是UTF-8字。它们是Unicode对象,而UTF-8是表示Unicode值的编码数据。它类似于在屏幕上显示图像并将其编码为PNG或JPEG文件,或datetime
对象并将此类对象编码为ISO-8601字符串。编码数据和值是相关的,但不是同一件事。在试图查找单个值时发现这很有用,但如果我们要搜索列表中的任何值,该怎么办?有了contains,我们就可以使用“|”。join,但这对contains不起作用find@EduardoPeFez我很难理解你的意思。或许可以问一个新问题?假设您想看看“string”是否有子字符串“st”或“ae”。您可以对series.contains('ae | st')执行此操作,然后字符串将返回true,因为它包含'st'。然而,在in中,我们只能搜索“st”或“ae”,但不能同时搜索两者time@EduardoPeFez是的,为此您需要使用正则表达式,或者使用带有列表理解的any
:any(fullstr中的substr表示substr in('ae','st'))