How to compare two string with some characters only in python
This question already has an answer here:
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