We can extract substring from a string. In this article, we would illustrate how to slice a string in Python v3.9. But before we proceed, it is important to discuss a bit about string indexing.
In the additional info section, we would discuss how Python strings are immutable i.e. they can’t be assigned values.
Indexing a string in Python
Lets say we have a variable x that has a string assigned –
>>> x = 'TechPiezo'
If we index a string from left, then index of the first character is 0 (zero). On the other hand, if indexing is done from right then index of the first character starts from -1.
On the Python interpreter, if we get the value of x at index 0 then –
>>> x [0]
would result in –
‘T’
Similarly, for others as well.
So, from the left it would be –
x [0] = T x [1] = e
and so on till –
x [8] = o
On the contrary, if its indexed from right then –
x [-1] = o x [-2] = z
till –
x [-9] = T
You would notice, we haven’t used x[0] when starting the index from right. That’s because there can’t be -0, zero is well a zero.
With indexing done, lets now move on to the how to slice a string.
Slice a string in Python
With the help of slicing, we can extract a substring from a string. We will continue with the same variable –
>>> x = 'TechPiezo'
Before we start, its going to be –
x [start:stop]
A. To extract a substring from the left–
>>> x [0:3]
would yield –
'Tec'
It important to note here that, character at the index 3 i.e. ‘h’ is excluded.
B. Similarly,
>>> x [3:6]
output –
'hPi'
C. But, if its extracted from the right –
>>> x [-6:-3]
it would be –
'hPi'
D. In case we want to slice string to the end, then it’s better to omit the second index –
>>> x [2:]
This would get us –
'chPiezo'
E. Or, what if we omit the first index
>>> x [:3]
it doesn’t include the character at the last index –
'Tec'
Step-wise slice a string in Python
The string we have sliced up till now had a step of 1. We can also define the step size for our substring.
x [start:stop:step]
Using the same variable again –
>>> x = 'TechPiezo'
Here, we define range 0-6 & step size as 2 instead of default 1.
>>> x [0:6:2]
It would result in –
'TcP'
It is worth mentioning here that, we can also reverse a string using negative step i.e. -1
>>> x[::-1]
Output –
'ozeiPhceT'
In conclusion, we have discussed how to slice a string in Python. Step-wise slicing and string reversal was also there.
Additional Info –
Python strings are immutable i.e. we can’t change the contents of the string once its assigned.
So, even if we try to modify our string it won’t.
>>> x = 'TechPiezo'
>>> x [3] = 'X'
It would say –
TypeError: 'str' object does not support item assignment