How to compare two string with some characters only in python

This question already has an answer here:

  • Compare strings in python like the sql “like” (with “%” and “_”) 2 answers
  • Does Python have a string 'contains' substring method? 13 answers

  • You could use in to check if a string is contained in an other:

    'toyota innova' in 'toyota innova 7' # True
    'tempo traveller' in 'tempo traveller 15 str' # True
    

    If you only want to match the start of the string, you can use str.startswith :

    'toyota innova 7'.startswith('toyota innova') # True
    'tempo traveller 15 str'.startswith('tempo traveller') # True
    

    Alternatively, if you only want to match the end of the string, you can use str.endswith

    'test with a test'.endswith('with a test') # True
    

    You can use .startswith() method.

    if s2.startswith(s1):
        return True
    

    or you may use in operator, as suggested by user312016


    You may also need to check if s2 in s1 like this:

    def my_cmp(s1, s2):
        return (s1 in s2) or (s2 in s1)
    

    Output:

    >>> s1 = "test1"
    >>> s2 = "test1 test2"
    >>>
    >>> my_cmp(s1, s2)
    True
    >>>
    >>> s3 = "test1 test2"
    >>> s4 = "test1"
    >>>
    >>> my_cmp(s3, s4)
    True
    
    链接地址: http://www.djcxy.com/p/74018.html

    上一篇: Python是否有一个字符串'contains'substring方法?

    下一篇: 如何比较两个字符串与只在python中的一些字符