String Slicing in Python
Python slicing is about obtaining a sub-string from the given string by slicing it respectively from start to end.
How String slicing in Python works
For understanding slicing we will use different methods, here we will cover 2 methods of string slicing, the one is using the in-build slice() method and another using the [:] array slice. String slicing in Python is about obtaining a sub-string from the given string by slicing it respectively from start to end.
Python slicing can be done in two ways:
- Using a slice() method
- Using array slicing [ : : ] method
Index tracker for positive and negative index: String indexing and slicing in python. Here, the Negative comes into consideration when tracking the string in reverse.
Method 1: Using slice() method
The slice() constructor creates a slice object representing the set of indices specified by range(start, stop, step).
- slice(start, stop, step)
Parameters: start: Starting index where the slicing of object starts. stop: Ending index where the slicing of object stops. step: It is an optional argument that determines the increment between each index for slicing. Return Type: Returns a sliced object containing elements in the given range only.
String slicing AST SR GITA
Method 2: Using List/array slicing [ : : ] method
In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and convenient way to slice a string using list slicing and Array slicing both syntax-wise and execution-wise. A start, end, and step have the same mechanism as the slice() constructor.
Below we will see string slicing in Python with example.
arr[start:stop] # items start through stop-1 arr[start:] # items start through the rest of the array arr[:stop] # items from the beginning through stop-1 arr[:] # a copy of the whole array arr[start:stop:step] # start through not past stop, by step
In this example, we will see slicing in python list the index start from 0 indexes and ending with a 2 index(stops at 3-1=2 ).
In this example, we will see the example of starting from 1 index and ending with a 5 index(stops at 3-1=2 ), and the skipping step is 2. It is a good example of Python slicing string by character.
In this example, we will see the example of starting from -1 indexes and ending with a -12 index(stops at 3-1=2 )and the skipping step is -2.
In this example, the whole string is printed in reverse order.
Note: To know more about strings click here.