24

I'm working on the MIT open courseware for python but have having a hard time with the following example:

To get started, we are going to use some built-in Python functions. To use these functions, include the statement from string import * at the beginning of your file. This will allow you to use Python string functions. In particular, if you want to find the starting point of the first match of a keyword string key in a target string target you could use thefind function. Try running on some examples, such as find("atgacatgcacaagtatgcat","atgc") Note how it returns the index of the first instance of the key in the target. Also note that if no instance of the key exists in the target, e.g, find("atgacatgcacaagtatgcat","ggcc") it returns the value -1.

The course in python 2.4 (or so) but I'm trying to do the assignments in Py3.. learning the differences along the way.

1
  • 5
    Using the string module functions instead of the string class methods has been deprecated since forever. That open courseware seriously need updating. Oct 2, 2011 at 5:46

5 Answers 5

30

Use the .find() method of a string, rather than string.find(). (This also works, and is probably preferable, in python 2).

1
  • 1
    Note that it returns -1 if it cannot find the substring, or its first position in the string (i.e. 0 .. length - 1).
    – jciloa
    Dec 14, 2017 at 11:27
9

Isn't it still just find? From the documentation:

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

Return the lowest index in the string where substring sub is found, such that sub is contained in the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

0
7
str = "Python"

In Python2:

string.find(str,"y")

In Python3:

str.find("y")
3

For Python2 and Python3:

if 'atgc' in 'atgacatgcacaagtatgcat':
    #do something
1
name = "ALIEN"      # complete String

letter = 'E'               # substring 

#string.find(substring[start:end])

name.find(letter[:])

Output : 3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.