Extracting Part of a String
You want to cut out a section of a string between certain character positions.
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.