We already saw that strings are a sequence of characters in Python, a substring is just a portion of a string.
For example, say “Hello World!” is a string, we can have the following substrings and more: “Hello”, “World”, “He”, etc. To know more about strings, please check out our tutorial on Python Strings.
Fortunately, Python provides various methods to get substrings from strings. In this section, we shall look in detail into these methods.
String Indexing
It is common for all programming languages to access items of an ordered set of data using a number representing the item’s position in that data. This process is called indexing. In Python, since strings are ordered sequences of characters, it fully supports this indexing mechanism.
We may think that as string indexing enables us to retrieve just a single character from a string, hence it can’t be referred to as substring. However, there is no representation of a single character in Python like there is in other programming languages like C. Python treats any element enclosed in single or double quotes as a string.
String indexing has been fully covered in our tutorial on Python String Operator and Methods.
String Slicing
In Python, string slicing enables us to extract substrings from a string by applying some complex manipulation of indices. This is one of the most powerful operations that sequences provide. String slicing has been fully covered in our tutorial on “Python String Operator and Methods“.
Early in this tutorial, in the Table 1 above, we saw the built-in function slice() which returns a slice object that can be used to slice a string.