String Slicing – How to Get a Substring From a String in Python?

Spread the love

String Slicing –

To get a substring from a string you can use string slicing.

Syntax –

string[start:end:step]

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.

Examples –

1 . Get the substring starting from the beginning till the 4th index or get the first 5 characters.

In [1]: string = 'Hello World'

In [2]: string[0:5]
Out[2]: 'Hello'

In [3]: # equivalent operation

In [4]: string[:5]
Out[4]: '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 [5]: string[-1]
Out[5]: 'd'

3. Get the last 5 characters –

In [6]: string[-5:]
Out[6]: 'World'

you can also omit the last index.

4 . Get a substring starting from 2nd index till the 5th index –

In [7]: string[2:6]
Out[7]: 'llo '

5. Get every other characters –

In [8]: string[::2]
Out[8]: 'HloWrd'

Rating: 1 out of 5.

Leave a Reply