unicode string equivalent of contain

前端 未结 4 1184
长情又很酷
长情又很酷 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.

    0 讨论(0)
  • 2021-02-12 11:23

    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 讨论(0)
  • 2021-02-12 11:30

    There is no difference between str and unicode.

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

    is basically the same.

    0 讨论(0)
  • 2021-02-12 11:30

    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")
    
    0 讨论(0)
提交回复
热议问题