The Basics of String Slicing in Python

What is string slicing?

String slicing is Python’s way of generating a substring. A substring is a part of a string. For example, “Hi there!” is a string and “there!” is a substring of the original string.

String slicing syntax

phrase = 'Python String Slicing'
phrase[0:6] # 'Python'
phrase[7:13] # 'String'
phrase[14:len(phrase)] # 'Slicing'

The code above defines Python’s string slicing syntax as: string[start index : end index]. Starting index is always included. This means that the starting index you provide is the character index that is used to begin the production of the substring. However, end index is excluded. In the example above, phrase[7:13] produces: String. The end index of 13 is the location of the space after the g in String. How does this code produce the output it does? Because end index is excluded, Python actually uses a value of end index - 1 (for positive indices) as its final index location. Therefore, phrase[7:13] is really phrase[7:12]. There are also default values that one must be aware of when performing string slicing.

phrase[:6]              # 'Python'
phrase[14:] # 'Slicing'
phrase[:] # 'Python String Slicing'
phrase[:8] + phrase[8:] # 'Python String Slicing'

The default starting index is zero and the default ending index is the length of the string. Values like 0 and len(phrase) can be omitted and still produce the same result as if they were in the statement. This convention guarantees that the statement: phrase[:x] + phrase[x:] will always result in phrase (the original string).

phrase[:-7] # 'Python String '
phrase[-7:] # 'Slicing'

Python also allows for negative indices to be used when creating substrings. Negative indices provide the ability to access a string by starting at the end of it instead of the beginning.

Using string slicing syntax on lists

even_list = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
first_half = even_list[:len(even_list) // 2] # [2, 4, 6, 8, 10]
second_half = even_list[len(even_list) // 2:] # [12, 14, 16, 18, 20]

All of the mechanisms used on strings to produce substrings can be applied on lists to produce sublists. The example above uses slicing to generate two new lists from each half of the original list. Generating substrings, and even sublists, has never been easier with Python.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store