Python find() Method

Python 字符串Python Strings


Description

The Python find() method checks whether the string contains the substring str. If the beg (beginning) and end (ending) range are specified, it checks whether the substring is contained within the specified range. If the substring is found, it returns the starting index; otherwise, it returns -1.

Syntax

The syntax of the find() method is:

str.find(str, beg=0, end=len(string))

Parameters

  • str -- The string to search for.
  • beg -- The starting index, default is 0.
  • end -- The ending index, default is the length of the string.

Return Value

If the substring is found, the starting index is returned; otherwise, -1 is returned.

Examples

The following example demonstrates the find() method:

Example (Python 2.0+)

#!/usr/bin/python str1 = "this is string example....wow!!!"; str2 = "exam"; print str1.find(str2); print str1.find(str2, 10); print str1.find(str2, 40);

The output of the above example is as follows:

15
15
-1

Example (Python 2.0+)

>>>info = 'abca' >>> print info.find('a') # Start from index 0, find the first occurrence of the substring in the string, return result: 0 0 >>> print info.find('a',1) # Start from index 1, find the first occurrence of the substring in the string: return result 3 3 >>> print info.find('3') # If not found, return -1 -1 >>>

Python 字符串Python Strings

Other Extensions