Slicing strings is one of the most common operations in Python. There are several ways to do it, but only three methods are used frequently. These three methods include slicing using [Start : End], [Start : End : Stepover] and negative indexing.
1. Slice String Using [Start : End]
Slice strings using [start : end]
The [start : end] syntax is used when you want to slice a string from its beginning. The start value is inclusive, meaning that it includes the character at that index location in the string. And, as we mentioned earlier, both start and end are zero-based. That means that the first character of a string has an index value of zero (not one). If either parameter (start or end) is omitted, then Python will use defaults for those values:
2. Slice String Using [Start : End : Stepover]
The second method is a combination of the first and second methods. This time, we specify the start index, end index, and stepover together:
In this case, we want to slice from the 3rd character to 5th character with a stepover of 2:
print(‘Length: ‘, len(str))
3. Negative Indexing in Python String
Negative indexing in Python is a very useful tool. It allows you to access a range of characters from the end of the string, instead of from the beginning.
Negative indexing starts from the end negative -1, and goes down until it reaches 0, which is equivalent to the first character in your string.
There are only three methods to slice a string in Python
There are only three methods to slice a string in Python.
- Slice String Using [Start : End]
- Slice String Using [Start : End : Stepover]
- Negative Indexing in Python String
There are only three methods to slice a string in Python. It makes sense to know how to slice strings in Python, because it is one of the most common types of data we can manipulate with code.