String Slicing

Slicing can be used to select a range of characters from a string. String slices are also called substrings.

To get a slice of a string, the following general format:

string[start : end]

The expression will return a string containing a copy of the characters from start up to (but not including) end.

Example:

full_name = 'Ashraf Mohammad'

middle_name = full_name[7:10]

The second statement assigns the string 'Moh' to the middle_name variable.

If start index is left out in a slicing expression, Python uses 0 as the starting index.

first_name = full_name[:5]

is same as

first_name = full_name[0:5]

If you leave out the end index in a slicing expression, Python uses the length of the string as the end index.

my_string = full_name[:]

is same as

my_string = full_name[0 : len(full_name)]

Negative numbers can also be used as indexes in slicing expressions to reference positions relative to the end of the string.

Invalid indexes do not cause slicing expressions to raise an exception. For example:

• If the end index specifies a position beyond the end of the string, Python will use the length of the string instead.

• If the start index specifies a position before the beginning of the string, Python will use 0 instead.

• If the start index is greater than the end index, the slicing expression will return an empty string.