Question 5.15: Extracting Part of a String You want to cut out a section of......

Extracting Part of a String

You want to cut out a section of a string between certain character positions.

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 Python [:] notation.

For example, to cut out a section from the second character to the fifth character of the string abcdefghi, you would use:

>>> s = “abcdefghi”
>>> s[1:5]
‘bcde’
>>>

Note that the character positions start at 0, so a position of 1 means the second character in the string and 5 means the sixth, but the character range is exclusive at the high end, so the letter f is not included in this example.

Discussion

The [:] notation is actually quite powerful. You can omit either argument, in which case, the start or end of the string is assumed as appropriate. For example:

>>> s[:5]
‘abcde’
>>>

and

>>> s = “abcdefghi”
>>> s[3:]
‘defghi’
>>>

You can also use negative indices to count back from the end of the string. This can be useful in situations such as when you want to find the three-letter extension of a file, as in the following example:

>>> “myfile.txt”[-3:]
‘txt’

See Also

Recipe 5.10 describes joining strings together rather than splitting them.

Recipe 6.10 uses the same syntax but with lists.

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.14

Verified Answer:

Use the find Python function. For example, to find...