String Slicing –
To get a substring from a string you can use string slicing.
start – the starting index of the substring
end – the end index of the substring. The character at this index is not included in the substring.
step – The step size of the slicing. The default value is 1.
1 . Get the substring starting from the beginning till the 4th index or get the first 5 characters.
In : string = 'Hello World' In : string[0:5] Out: 'Hello' In : # equivalent operation In : string[:5] Out: 'Hello'
We can also omit the starting index which means from the start of the string. Here the end index is 5 but the character at this index is not included.
2. Get the last character –
In : string[-1] Out: 'd'
3. Get the last 5 characters –
In : string[-5:] Out: 'World'
you can also omit the last index.
4 . Get a substring starting from 2nd index till the 5th index –
In : string[2:6] Out: 'llo '
5. Get every other characters –
In : string[::2] Out: 'HloWrd'