Python string contains check

To check if a string is part of another string (case sensitive) we can use these approaches

  • Using in operator
  • Using string find() method
    ## if start and end are present then search from start till end-1
    s.find(sub[, start[, end]])
    
  • Using strng index() method. It is similar to find but raises ValueError. Its better to avoid it.
    ## if start and end are present then search from start till end-1
    s.index(sub[, start[, end]])
    

Case insensitive check

To do case insensitive check, both string can be converted to lowercase.

Example – contains check using in operator

s = "Hello Python"
sub = "Hello"
if sub in s:
  print "found"
found
Env: Python 2.7.6

Example – contains check using find(sub)

s = "Hello Python"
sub = "Hello"
if s.find(sub) >= 0:
  print "found at %s" % (s.find(sub))
found at 0
Env: Python 2.7.6

Example – contains check using index(sub)

Since this raises ValueError, it is better to use above approaches.

s = "Hello Python"
sub = "Hello2"
try:
  if s.index(sub) >= 0:
    print "found at %s" % (s.index(sub))
except ValueError as e:
  print str(e)
substring not found
Env: Python 2.7.6

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments