23

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?

Example with normal ASCII string

s = "haha i am going home"
k = "haha"

if s.contains(k):
    print "contains"

I am using python 2.7.x

1
  • u'...' objects are not UTF-8 words. They are Unicode objects, while UTF-8 is encoded data representing Unicode values. It is comparable to displaying an image on the screen and encoding it into a PNG or JPEG file, or a datetime object and encoding such objects to a ISO-8601 string. The encoded data and the value are related, but not the same thing. Commented Apr 5, 2015 at 12:03

4 Answers 4

39

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.

5
  • Found this useful when trying to find one single value but what if we want to search for any value in a list? With contains we would be able to use '|'.join but that wont work with find Commented Nov 28, 2019 at 10:10
  • @EduardoPeFez I'm having trouble figuring out what you mean. Perhaps ask in a new question?
    – frnhr
    Commented Nov 28, 2019 at 15:59
  • lets say that you want to see if 'string' has either substring 'st' or 'ae'. You would be able to do this with series.contains('ae|st') then string would return true as it contains 'st'. However with in we can only search either for 'st' or 'ae' but not both at the same time Commented Mar 10, 2020 at 19:32
  • @EduardoPeFez Yeah, for that you would need to use a regex, or use any with a list comprehension: any(substr in fullstr for substr in (‘ae’, ‘st’))
    – frnhr
    Commented Mar 10, 2020 at 23:37
  • bool(re.search('(re)|(st)', fullstr))
    – frnhr
    Commented Mar 10, 2020 at 23:46
8

There is no difference between str and unicode.

print u"ábc" in u"some ábc"
print "abc" in "some abc"

is basically the same.

5

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

0

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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.