Strings in Python are iterable
1
2
3
>>> a = "Hello"
>>> a[0]
'H'
As you could see the count starts from 0 and goes in increamental
1
2
3
4
5
>>> a = "Hello"
>>> a[0]
'H'
>>> a[1]
'e'
String slicing
Syntax to perform string slicing is string[start:stop:step]
start is the start position stop is the stop position - if we give 3 then it would print till 2nd position step is the increament
The index of string is followed as below
H E L L O
0 1 2 3 4 -> Left to Right
0 -1 -2 -3 -4 <- Right to Left
1
2
3
>>> b = "abcdefgh"
>>> b[:2]
'ab'
| Not all start , stop and end are mandatory if any parameter is not passed then max value is applied as default
1
2
3
>>> b = "abcdefgh"
>>> b[2:5]
'cde'
| Above it printed from 2nd position (c) to one before 5 which is 4 (e)
1
2
3
>>> b = "abcdefgh"
>>> b[2:7:2]
'ceg'
| In above you could see it’s increamented as 2 ie) from cdefg it printed the 2nd characters (ceg)
1
2
3
>>> b = "abcdefgh"
>>> b[::-1]
'hgfedcba'
| Adding -1 or -ve number in step process the data from right to left. This result in reversal of string
Thanks for reading till end.
Followus on insta @techpechu
Join Our Discord
We do run a youtube channel in Indian regional language Tamil called TechPechu. Do subscribe us for moral support. Happy Learning.