Unicode String Equivalent Of Contain
I have an error when trying to use contain in python. s = u'some utf8 words' k = u'one utf8 word' if s.contains(k): print 'contains' How do i achieve the same result? Examp
Solution 1:
The same for ascii and utf8 strings:
if k in s:
print "contains"
There is no contains()
on either ascii or uft8 strings:
>>> "strrtinggg".contains
AttributeError: 'str' object has no attribute 'contains'
What you can use instead of contains
is find
or index
:
if k.find(s) > -1:
print "contains"
or
try:
k.index(s)
except ValueError:
pass # ValueError: substring not found
else:
print "contains"
But of course, the in
operator is the way to go, it's much more elegant.
Solution 2:
There is no difference between str
and unicode
.
print u"ábc" in u"some ábc"
print "abc" in "some abc"
is basically the same.
Solution 3:
Strings don't have "contain" attribute.
s = "haha i am going home"
s_new = s.split(' ')
k = "haha"
if k in s_new:
print "contains"
I guess you want to achieve this
Solution 4:
Testing of string existance in string
string = "Little bear likes beer"
if "beer" in string:
print("Little bear likes beer")
else:
print("Little bear is driving")
Post a Comment for "Unicode String Equivalent Of Contain"