In the last blog, we had discussed on strings literals and their basic operations. Now, In round 2 of strings we will be discussing on slicing the string,
Slicing and Indexing
What is a list?
→ List a data type in Python which can modified without creating a new ones.
List is defined by using square brackets surrounding with the zero or more elements.
We know that Strings are ordered collections of characters, the characters in the strings can be fetched by Indexing, which means if we provide a number in the square brackets the element related to that index will be used.
Like in another languages,python numbering or offset starts from zero and ends one less than the length of the string but python is special in the sense that the items can be fetched even using the negative numbers. It will be clear from the following example:
>>> var='python' >>> var 'p' >>> var 'n' >>> var[-1],var[-5] ('n', 'y') >>> var,var ('n', 'y')
Lets examine the example here, the string python is assigned to var. var and var fetches the first and last character of the string python. Var[-1] and var[-5] fetches the characters from backwards, technically speaking, (6-1)=5th index and (6-5)=1st index of the string.
There is a generalized form of indexing called Slicing, which can be used to extract a section of the sequence. To be specific it can be used to extract multiple characters in a single step, when this is applied to strings. We normally use slicing to extract a column of data, chop off leading and trailing text, and more.
Syntax: variable_name[beginning of the slice : end of the slice ]
>>>var='python' >>> var[1:3] 'yt' >>> var="monty python" >>> var[1:],var[:5] ('onty python', 'monty')
If we examine the code, the second line extracts the characters from 1 to 3rd index, i.e. returns a new string from 2nd item to 4th item. var[1:] returns all the elements beyond the first, so m is not included in the output onty python and var[:5] returns all the element before the 5th index.
>>> var[:-1] 'monty pytho'
returns all elements except the last element.
if we try to access a element which is out of range, we get the error like this:
>>> var Traceback (most recent call last): File "<pyshell#20>", line 1, in <module> var IndexError: string index out of range
So lets summarise:
1)Indexing: fetches single characters from the index specified
- The index starts from zero, i.e. first item is placed in zeroth position.
- Negative indexes are used to fetch characters from backward.
2)Slicing: fetches multicharacters or an entire section in one go.
Syntax:Variable_name[upper bound:lower bound]
- If the bound or index is not mentioned then it takes by default as zero.
Extended slicing: the third limit
Slice expression supports optional third index(called as step or stride), which increments the index by that value. Overall expression can be generalized as X[I:J:K], which means “extract all the items in X, from offset I through J−1, by K”.
>>> special='three indexes' >>> special[1:10:2] 'he ne' >>> special[-5:-1:1] 'dexe'
There’s another thing which we must know i.e. strings can also be sequences, by just adding the index within the square brackets at the end of the string. Take for instance
>>> 'Python is an interpreted language' 'n' >>> 'Python' 'h'
Strings: Immutable Sequence!?
In previous blog, we have discussed about immutable sequences(character at a specific position cannot be replaced).
>>> var='alpha' >>> var='bravo' Traceback (most recent call last): File "<pyshell#22>", line 1, in <module> var='bravo' TypeError: 'str' object does not support item assignment
We have a situation here, so how do we modify the character in the string? Lets use some of the superpowers of python, by using a string method replace()
Syntax:Variable_name.replace(a section of string to replace,string to be replaced by)
>>> string="monday" >>> string.replace('day','ty') #day is replaced by ty 'monty'
Another method to modify a string is by using traditional method, what I meant by that is by using concatentation, slicing and indexing.
>>> string="help!" >>> string=string[-1]+string[:-1]+'me'+string[-1] >>> string '!helpme!'
In the next blog it will be all about String methods which makes your working with strings and other functions easier and then end it with String Formatting, in which multiple expression can be handled easily.