unicode string equivalent of contain

前端 未结 4 1193
长情又很酷
长情又很酷 2021-02-12 11:01

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\" 
4条回答
  •  春和景丽
    2021-02-12 11:12

    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.

提交回复
热议问题