Question 5.14: Find the Position of One String Inside Another You need to f......

Find the Position of One String Inside Another

You need to find the position of one string within another.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

Use the find Python function.

For example, to find the starting position of the string def within the string abcdef ghi, you would use:

>>> s = “abcdefghi”
>>> s.find(“def”)
3
>>>

Note that the character positions start at 0, so a position of 3 means the fourth character in the string.

Discussion

If the string you’re looking for doesn’t exist in the string being searched, then find returns the value -1.

See Also

The replace function is used to both find and then replace all occurrences of a string (Recipe 5.16).

Related Answered Questions

Question: 5.24

Verified Answer:

Create a function that groups together lines of co...
Question: 5.23

Verified Answer:

Use the Python break statement to exit either a wh...
Question: 5.22

Verified Answer:

Use the Python while statement. The while statemen...
Question: 5.21

Verified Answer:

Use the Python for command and iterate over a rang...
Question: 5.20

Verified Answer:

Use one of the logical operators: and, or, and not...
Question: 5.19

Verified Answer:

Use one of the comparison operators: <, >, &...
Question: 5.17

Verified Answer:

Use the upper or lower function as appropriate. Fo...
Question: 5.18

Verified Answer:

Use the Python if command. The following example w...
Question: 5.15

Verified Answer:

Use the Python [:] notation. For example, to cut o...