Python string find method

Search a sub string

The find method searches a substring within a larger string. It returns the leftmost index where the substring is found, or -1 if not found.

The syntax for string find method is

s.find(sub, [, start [, end]])

It returns offset of the first occurrence of string sub in s, between offsets start and end (which default to 0 and len(s), the entire string). Returns -1 if not found.


print 'www.java2s.com'.find('com') 
title = "www.java2s.com Python" 
print title.find('2s') 
print title.find('java') 
print title.find('Python') 
print title.find('Javascript')

The code above generates the following result.


S = 'xxxxSPAMxxxxSPAMxxxx'
where = S.find('SPAM')          # search for position
print where                           
S = S[:where] + 'EGGS' + S[(where+4):]
print S# from   ww  w  .  ja v a 2  s  .  c om

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary