![]() |
VOOZH | about |
String slicing in Python is a way to get specific parts of a string by using start, end and step values. It’s especially useful for text manipulation and data parsing.
Let’s take a quick example of string slicing:
Hello
Explanation: In this example, we used the slice s[0:5] to obtain the substring "Hello" from the original string.
substring = s[start : end : step]
Parameters:
Return Type: The result of a slicing operation is always a string (str type) that contains a subset of the characters from the original string.
Negative indexing is useful for accessing elements from the end of the String. The last element has an index of -1, the second last element -2 and so on.
Below example shows how to use negative numbers to access elements from the string starting from the end. Negative indexing makes it easy to get items without needing to know the exact length of the string.
lmno abcdefghijkl klm hjln
Explanation:
To reverse a string, use a negative step value of -1, which moves from the end of the string to the beginning.
nohtyP
Explanation: The slice s[::-1] starts from the end and steps backward through the string, which effectively reversing it. This method does not alter the original string.
Let’s see how to use string slicing in Python with the examples below:
To retrieve the entire string, use slicing without specifying any parameters.
Hello, World! Hello, World!
Explanation: Using [:] or [::] without specifying start, end or step returns the complete string.
To get all the items from a specific position to the end of the string, we can specify the start index and leave the end blank.
And to get all the items before a specific index, we can specify the end index while leaving start blank.
World! Hello
Explanation: The slice s[7:] starts from index 7 and continues to the end of the string.
To extract characters between specific positions, provide both start and end indices.
ello
Explanation: The code slices the string s to extract characters starting from index 1 up to, but not including, index 5, resulting in the substring "ello".
To retrieve characters at regular intervals, use the step parameter.
acegi beh
Explanation: The slice s[::2] takes every second character from the string.