Indexing and Slicing:
In Python, the elements of ordered sequences like strings or lists can be -individually- accessed through their indices. This can be achieved by providing the numerical index of the element we wish to extract from the sequence. Additionally, Python supports slicing that is a characteristic that lets us extract a subset of the original sequence object.
In python sequence data types, we can access elements by indexing and slicing. Sequence data types are strings, list, tuple, range objects.
What are Indexing and Slicing?
Indexing: Indexing is used to obtain individual elements.
Slicing: Slicing is used to obtain a sequence of elements.
Indexing and Slicing can be be done in Python Sequences types like list, string, tuple, range objects.
Indexing
Indexing starts from 0
. Index 0
represents the first element in the sequence.
Negative indexing starts from -1. Index -1
represents the last element in the sequence.
Indexing in string
Indexing in strings
Example of Indexing in strings
s="Python"
print (s[0])#Output:P
print (s[-1])#Output:n
print (s[-2])#Output:o
Indexing in List
Indexing in List
Example of Indexing in List
list_=[10,20,30,40,50]
print (list_[0])#Output:10
print (list_[-1])#Output:50
print (list_[-2])#Output:40
Indexing in tuple and range object
#Indexing - tuple
t=(1,2,3,4,5)
print (t[0])#Output:1
print (t[-1])#Output:5
print (t[-2])#Output:4#Indexing - range object
r=range(5)
print (r[0])#Output:0
print (r[-1])#Output:4
print (r[-2])#Output:3
Slicing:
- Slicing (Range Of Indexes):
We can specify a range of indexes.
s[i:j:k] — slice of s from i to j with step k
Slicing Strings
slicing allows you to obtain substring
1. s[1:3]
— Returns element from the first index to the third index(excluded).
s=”Python”
print (s[1:3])
#Output:yt
2. s[0:3]
-Returns element from the beginning of the string till the third index(excluded).
s=”Python”
print (s[0:3])
#Output:Pyt
3. Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.
Omitted start index:
s[:4]
-Returns element from the beginning of the string till the third index.
s="Python"
print (s[:4])
#Output:Pyth
Omitted stop index:
s[2:]
-Returns element from the second index till the end of the string.
s="Python"
print (s[2:])
#Output:thon
4. Negative index.
s[-2:]
-Returns element from second last index till the end of the string
s="Python"
print (s[-2:])
#Output:on
5.Using step-index.
s[1:5:2]
-Returns element from index 1 till index 5(excluded) using step 2.
s="Python"
print (s[1:5:2])
#Output:yh
Image Source: Author
6.Out of range index.
Out of range indexes are handled gracefully when used for slicing.
s="Python"
print (s[10:])
#Output:''
Slicing List:
Slicing List returns a new list containing requested elements.
- Shallow copy.
n[:] -Returns shallow copy of the list.
n=[0,1,2,3,4,5]
print(n[:])
#Output:[0, 1, 2, 3, 4, 5]
Refer to my story for shallow copy.
2. n[1:3]
-Returns new list containing elements from index 1 till index 3(excluded)
n=[0,1,2,3,4,5]
print(n[1:3])
#Output:[1, 2]
3.Omitted stop index
n[1:]
-Returns a new list containing elements from the first index till the end of the list.
n=[0,1,2,3,4,5]
print(n[1:])
#Output:[1, 2, 3, 4, 5]
4. Omitted start index
n[:4]
-Returns new list containing elements from the beginning of the list till the third index
n=[0,1,2,3,4,5]
print(n[:4])
#Output:[0, 1, 2, 3]
5. Slicing returns a new list but indexing returns the item only.
n[1:2]
-Returns a new list containing an element from index 1.n
s[1]
-Returns the element at index 1
n=[0,1,2,3,4,5]
print(n[1:2])
#Output:[1]
print (n[1])
#Output:1
6.Using step:
n[1:5:2]
-Returns new list containing an element from index 1 till index 5(excluded) using step 2.
n=[0,1,2,3,4,5]
print(n[1:5:2])
#Output:[1,3]
Exception Handling in Python
The cause of an exception is often external to the program itself. For example, an incorrect input, a malfunctioning IO device etc. Because the program abruptly terminates on encountering an exception, it may cause damage to system resources, such as files. Hence, the exceptions should be properly handled so that an abrupt termination of the program is prevented.
Python uses try
and except
keywords to handle exceptions. Both keywords are followed by indented blocks.
Syntax:
try :
#statements in try block
except :
#executed when error in try block
The try: block contains one or more statements which are likely to encounter an exception. If the statements in this block are executed without an exception, the subsequent except: block is skipped.
If the exception does occur, the program flow is transferred to the except: block. The statements in the except:
block are meant to handle the cause of the exception appropriately. For example, returning an appropriate error message.
You can specify the type of exception after the except
keyword. The subsequent block will be executed only if the specified exception occurs. There may be multiple except clauses with different exception types in a single try block. If the type of exception doesn't match any of the except blocks, it will remain unhand-led and the program will terminate.
The rest of the statements after the except block will continue to be executed, regardless if the exception is encountered or not.
Regular Expressions in Python
In Python, regular expressions are supported by the re module. That means that if you want to start using them in your Python scripts, you have to import this module with the help of import
:
import re
Raw strings
Different functions in Python’s re module use raw string as an argument. A normal string, when prefixed with ‘r’ or ‘R’ becomes a raw string.
Example: Raw String
Copy
>>> rawstr = r'Hello! How are you?'
>>> print(rawstr)
Hello! How are you?
The difference between a normal string and a raw string is that the normal string in print() function translates escape characters (such as \n
, \t
etc.) if any, while those in a raw string are not.
Example: String vs Raw String
Copy
str1 = "Hello!\nHow are you?"
print("normal string:", str1)
str2 = r"Hello!\nHow are you?"
print("raw string:",str2)
Output
normal string: Hello!
How are you?
raw string: Hello!\nHow are you?
In the above example, \n
inside str1
(normal string) has translated as a newline being printed in the next line. But, it is printed as \n
in str2
- a raw string.
meta characters
Some characters carry a special meaning when they appear as a part pattern matching string. In Windows or Linux DOS commands, we use * and ? — they are similar to meta characters. Python’s re module uses the following characters as meta characters:
. ^ $ * + ? [ ] \ | ( )
When a set of alpha-numeric characters are placed inside square brackets []
, the target string is matched with these characters. A range of characters or individual characters can be listed in the square bracket. For example:
PatternDescription[abc]match any of the characters a, b, or c[a-c]which uses a range to express the same set of characters.[a-z]match only lowercase letters.[0–9]match only digits.
re.match() function
This function in re
module tries to find if the specified pattern is present at the beginning of the given string.
re.match(pattern, string)
The function returns None, if the given pattern is not in the beginning, and a match objects if found.
Example: re.match()
Copy
from re import matchmystr = "Welcome to TutorialsTeacher"
obj1 = match("We", mystr)
print(obj1)
obj2 = match("teacher", mystr)
print(obj2)
Output
<re.Match object; span=(0, 2), match='We'>
None
The match object has start
and end
properties.
Example:
Copy
>>> print("start:", obj.start(), "end:", obj.end())
Output
start: 0 end: 2
The following example demonstrates the use of the range of characters to find out if a string starts with ‘W’ and is followed by an alphabet.
Example: match()
Copy
from re import matchstrings=["Welcome to TutorialsTeacher", "weather forecast","Winston Churchill", "W.G.Grace","Wonders of India", "Water park"]for string in strings:
obj = match("W[a-z]",string)
print(obj)
Output
<re.Match object; span=(0, 2), match='We'>
None
<re.Match object; span=(0, 2), match='Wi'>
None
<re.Match object; span=(0, 2), match='Wo'>
<re.Match object; span=(0, 2), match='Wa'>
re.search() function
The re.search()
function searches for a specified pattern anywhere in the given string and stops the search on the first occurrence.
Example: re.search()
Copy
from re import searchstring = "Try to earn while you learn"obj = search("earn", string)
print(obj)
print(obj.start(), obj.end(), obj.group())
7 11 earn
Output
<re.Match object; span=(7, 11), match='earn'>
This function also returns the Match
object with start and end attributes. It also gives a group of characters of which the pattern is a part of.
re.findall() Function
As against the search()
function, the findall()
continues to search for the pattern till the target string is exhausted. The object returns a list of all occurrences.
Example: re.findall()
Copy
from re import findallstring = "Try to earn while you learn"obj = findall("earn", string)
print(obj)
Output
['earn', 'earn']
This function can be used to get the list of words in a sentence. We shall use \W* pattern for the purpose. We also check which of the words do not have any vowels in them.
Example: re.findall()
Copy
obj = findall(r"\w*", "Fly in the sky.")
print(obj)for word in obj:
obj= search(r"[aeiou]",word)
if word!='' and obj==None:
print(word)
Output
['Fly', '', 'in', '', 'the', '', 'sky', '', '']
Fly
sky
re.finditer() function
The re.finditer()
function returns an iterator object of all matches in the target string. For each matched group, start and end positions can be obtained by span() attribute.
Example: re.finditer()
Copy
from re import finditerstring = "Try to earn while you learn"
it = finditer("earn", string)
for match in it:
print(match.span())
Output
(7, 11)
(23, 27)
re.split() function
The re.split()
function works similar to the split() method of str
object in Python. It splits the given string every time a white space is found. In the above example of the findall()
to get all words, the list also contains each occurrence of white space as a word. That is eliminated by the split()
function in re
module.
Example: re.split()
Copy
from re import splitstring = "Flat is better than nested. Sparse is better than dense."
words = split(r' ', string)
print(words)
Output
['Flat', 'is', 'better', 'than', 'nested.', 'Sparse', 'is', 'better', 'than', 'dense.']
re.compile() Function
The re.compile()
function returns a pattern object which can be repeatedly used in different regex functions. In the following example, a string 'is' is compiled to get a pattern object and is subjected to the search()
method.
Example: re.compile()
Copy
from re import *pattern = compile(r'[aeiou]')
string = "Flat is better than nested. Sparse is better than dense."
words = split(r' ', string)
for word in words:
print(word, pattern.match(word))
Output
Flat None
is <re.Match object; span=(0, 1), match='i'>
better None
than None
nested. None
Sparse None
is <re.Match object; span=(0, 1), match='i'>
better None
than None
dense. None
The same pattern object can be reused in searching for words having vowels, as shown below.
Example: search()
Copy
for word in words:
print(word, pattern.search(word))
Output
Flat <re.Match object; span=(2, 3), match='a'>
is <re.Match object; span=(0, 1), match='i'>
better <re.Match object; span=(1, 2), match='e'>
than <re.Match object; span=(2, 3), match='a'>
nested. <re.Match object; span=(1, 2), match='e'>
Sparse <re.Match object; span=(2, 3), match='a'>
is <re.Match object; span=(0, 1), match='i'>
better <re.Match object; span=(1, 2), match='e'>
than <re.Match object; span=(2, 3), match='a'>
dense. <re.Match object; span=(1, 2), match='e'>