Searching strings for a substring. : substring « String « Python Tutorial






# counting the occurrences of a substring
string1 = "Test1, test2, test3, test4, Test5, test6"

print '"test" occurs %d times in \n\t%s' % ( string1.count( "test" ), string1 )
print '"test" occurs %d times after 18th character in \n\t%s' % ( string1.count( "test", 18, len( string1 ) ), string1 )
print

# finding a substring in a string
string2 = "Odd or even"

print '"%s" contains "or" starting at index %d' % ( string2, string2.find( "or" ) )

# find index of "even"
try:
   print '"even" index is', string2.index( "even" )
except ValueError:
   print '"even" does not occur in "%s"' % string2

if string2.startswith( "Odd" ):
   print '"%s" starts with "Odd"' % string2

if string2.endswith( "even" ):
   print '"%s" ends with "even"\n' % string2








5.35.substring
5.35.1.Searching strings for a substring.