foote

Does Python have a string 'contains' substring method?


 You can use the in operator:

if "blah" not in somestring: 
    continue

If it's just a substring search you can use string.find("substring").

You do have to be a little careful with findindex, and in though, as they are substring searches. In other words, this:

s = "This be a string"
if s.find("is") == -1:
    print("No 'is' here!")
else:
    print("Found 'is' in the string.")

It would print Found 'is' in the string. Similarly, if "is" in s: would evaluate to True. This may or may not be what you want.


99% of use cases will be covered using the keyword, in, which returns True or False:

'substring' in any_string

For the use case of getting the index, use str.find (which returns -1 on failure, and has optional positional arguments):

start = 0
stop = len(any_string)
any_string.find('substring', start, stop)

or str.index (like find but raises ValueError on failure):

start = 100 
end = 1000
any_string.index('substring', start, end)

Explanation

Use the in comparison operator because

  1. the language intends its usage, and
  2. other Python programmers will expect you to use it.
>>> 'foo' in '**foo**'
True

The opposite (complement), which the original question asked for, is not in:

>>> 'foo' not in '**foo**' # returns False
False

This is semantically the same as not 'foo' in '**foo**' but it's much more readable and explicitly provided for in the language as a readability improvement.

Does Python have a string 'contains' substring method? Does Python have a string 'contains' substring method? Reviewed by Udochi V.C on January 02, 2022 Rating: 5

No comments:

Powered by Blogger.