Round 2 of Strings in Python

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:

[python]
>>> var=’python’
>>> var[0]
‘p’
>>> var[5]
‘n’
>>> var[-1],var[-5]
(‘n’, ‘y’)
>>> var[5],var[1]
(‘n’, ‘y’)
[/python]

Lets examine the example here, the string python is assigned to var. var[0] and var[5] 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 ]

[python]
>>>var=’python’
>>> var[1:3]
‘yt’
>>> var="monty python"
>>> var[1:],var[:5]
(‘onty python’, ‘monty’)
[/python]

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.

[python]
>>> var[:-1]
‘monty pytho’
[/python]

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:

[python]
>>> var[19]
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
var[19]
IndexError: string index out of range
[/python]

So lets summarise:

1)Indexing: fetches single characters from the index specified

Syntax:Variable_name[index]

  • 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”.

[python]
>>> special=’three indexes’
>>> special[1:10:2]
‘he ne’
>>> special[-5:-1:1]
‘dexe’
[/python]

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]
>>> ‘Python is an interpreted language’[14]
‘n’
>>> ‘Python’[3]
‘h’
[/python]

Strings: Immutable Sequence!?

In previous blog, we have discussed about immutable sequences(character at a specific position cannot be replaced).

[python]
>>> var=’alpha’
>>> var[2]=’bravo’
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
var[2]=’bravo’
TypeError: ‘str’ object does not support item assignment
[/python]

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)

[python]
>>> string="monday"
>>> string.replace(‘day’,'ty’) #day is replaced by ty
‘monty’
[/python]

Another method to modify a string is by using traditional method, what I meant by that is by using concatentation, slicing and indexing.

[python]
>>> string="help!"
>>> string=string[-1]+string[:-1]+’me’+string[-1]
>>> string
‘!helpme!’
[/python]

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.

Advertisement