Python Maps
Python Maps
Python Maps also called ChainMap is a type of data structure to manage multiple
dictionaries together as one unit. The combined dictionary contains the key and
value pairs in a specific sequence eliminating any duplicate keys. The best use of
ChainMap is to search through multiple dictionaries at a time and get the proper
key-value pair mapping. We also see that these ChainMaps behave as stack data
structure.
Creating a ChainMap
We create two dictionaries and club them using the ChainMap method from the
collections library. Then we print the keys and values of the result of the
combination of the dictionaries. If there are duplicate keys, then only the value from
the first key is preserved.
import collections
print('Keys = {}'.format(list(res.keys())))
print('Values = {}'.format(list(res.values())))
print()
elements:
day1 = Mon
day3 = Wed
day2 = Tue
day3 in res: True
day4 in res: False
Map Reordering
If we change the order the dictionaries while clubbing them in the above example
we see that the position of the elements get interchanged as if they are in a
continuous chain. This again shows the behaviour of Maps as stacks.
import collections
print(res1.maps,'\n')
print(res2.maps,'\n')
Updating Map
When the element of the dictionary is updated, the result is instantly updated in the
result of the ChainMap. In the below example we see that the new updated value
reflects in the result without explicitly applying the ChainMap method again.
import collections
print(res.maps,'\n')
dict2['day4'] = 'Fri'
print(res.maps,'\n')
Previous Page
Next Page
A linked list is a sequence of data elements, which are connected together via links.
Each data element contains a connection to another data element in form of a
pointer. Python does not have linked lists in its standard library. We implement the
concept of linked lists using the concept of nodes as discussed in the previous
chapter. We have already seen how we create a node class and how to traverse the
elements of a node. In this chapter we are going to study the types of linked lists
known as singly linked lists. In this type of data structure there is only one link
between any two data elements. We create such a list and create additional
methods to insert, update and remove elements from the list.
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list1.headval.nextval = e2
class SLinkedList:
def __init__(self):
self.headval = None
def listprint(self):
printval = self.headval
while printval is not None:
print (printval.dataval)
printval = printval.nextval
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.listprint()
class SLinkedList:
def __init__(self):
self.headval = None
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.headval.nextval = e2
e2.nextval = e3
list.AtBegining("Sun")
list.listprint()
class SLinkedList:
def __init__(self):
self.headval = None
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
list.headval.nextval = e2
e2.nextval = e3
list.AtEnd("Thu")
list.listprint()
NewNode = Node(newdata)
NewNode.nextval = middle_node.nextval
middle_node.nextval = NewNode
list = SLinkedList()
list.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Thu")
list.headval.nextval = e2
e2.nextval = e3
list.Inbetween(list.headval.nextval,"Fri")
list.listprint()
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class SLinkedList:
def __init__(self):
self.head = None
HeadVal = self.head
if (HeadVal == None):
return
prev.next = HeadVal.next
HeadVal = None
def LListprint(self):
printval = self.head
while (printval):
print(printval.data),
printval = printval.next
llist = SLinkedList()
llist.Atbegining("Mon")
llist.Atbegining("Tue")
llist.Atbegining("Wed")
llist.Atbegining("Thu")
llist.RemoveNode("Tue")
llist.LListprint()
def __init__(self):
self.stack = []
def peek(self):
return self.stack[-1]
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.peek()
print(AStack.peek())
AStack.add("Wed")
AStack.add("Thu")
print(AStack.peek())
class Stack:
def __init__(self):
self.stack = []
AStack = Stack()
AStack.add("Mon")
AStack.add("Tue")
AStack.add("Wed")
AStack.add("Thu")
print(AStack.remove())
print(AStack.remove())
Python - Queue
We are familiar with queue in our day to day life as we wait for a service. The queue
data structure aslo means the same where the data elements are arranged in a
queue. The uniqueness of queue lies in the way items are added and removed. The
items are allowed at on end but removed form the other end. So it is a First-in-First
out method. An queue can be implemented using python list where we can use the
insert() and pop() methods to add and remove elements. Their is no insertion as
data elements are always added at the end of the queue.
Adding Elements to a Queue
In the below example we create a queue class where we implement the First-in-
First-Out method. We use the in-built insert method for adding data elements.
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
def size(self):
return len(self.queue)
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.size())
class Queue:
def __init__(self):
self.queue = list()
def addtoq(self,dataval):
# Insert method to add element
if dataval not in self.queue:
self.queue.insert(0,dataval)
return True
return False
# Pop method to remove element
def removefromq(self):
if len(self.queue)>0:
return self.queue.pop()
return ("No elements in Queue!")
TheQueue = Queue()
TheQueue.addtoq("Mon")
TheQueue.addtoq("Tue")
TheQueue.addtoq("Wed")
print(TheQueue.removefromq())
print(TheQueue.removefromq())
Stack
A Stack is a data structure that follows the LIFO(Last In First Out) principle. To
implement a stack, we need two simple operations:
o Adding - It adds the items in the stack and increases the stack size. The
addition takes place at the top of the stack.
o Deletion - It consists of two conditions, first, if no element is present in the
stack, then underflow occurs in the stack, and second, if a stack contains
some elements, then the topmost element gets removed. It reduces the stack
size.
o Traversing - It involves visiting each element of the stack.
Characteristics:
o Duplicacy is allowed.
Code
Output:
Queue
A Queue follows the First-in-First-Out (FIFO) principle. It is opened from both the
ends hence we can easily add elements to the back and can remove elements from
the front.
o Addition - It adds the element in a queue and takes place at the rear end,
i.e., at the back of the queue.
o Deletion - It consists of two conditions - If no element is present in the
queue, Underflow occurs in the queue, or if a stack contains some elements
then element present at the front gets deleted.
o Traversing - It involves to visit each element of the queue.
Characteristics
o Duplicacy is allowed.
o Useful for parsing CPU task operations.
Note: The implementation of a queue is a little bit different. A queue follows the
"First-In-First-Out". Time plays an important factor here. The Stack is fast because
we insert and pop the elements from the end of the list, whereas in the queue, the
insertion and pops are made from the beginning of the list, so it becomes slow.
The cause of this time difference is due to the properties of the list, which is fast
in the end operation but slow at the beginning operations because all other
elements have to be shifted one by one.
Code
1. import queue
2. # Queue is created as an object 'L'
3. L = queue.Queue(maxsize=10)
4.
5. # Data is inserted in 'L' at the end using put()
6. L.put(9)
7. L.put(6)
8. L.put(7)
9. L.put(4)
10.# get() takes data from
11.# from the head
12.# of the Queue
13.print(L.get())
14.print(L.get())
15.print(L.get())
16.print(L.get())
Output:
9
6
7
4
Python filter()
The filter() method constructs an iterator from elements of an iterable for
which a function returns true.
In simple words, filter() method filters the given iterable with the help of a
function that tests each element in the iterable to be true or not.
The syntax of filter() method is:
filter(function, iterable)
filter() Parameters
filter() method returns an iterator that passed the function check for each
element in the iterable.
filter() method is equivalent to:
# list of letters
letters = ['a', 'b', 'd', 'e', 'i', 'j', 'o']
if(letter in vowels):
return True
else:
return False
Output
Here, we have a list of letters and need to filter out only the vowels in it.
We could use a for loop to loop through each element in letters list and
store it in another list, but in Python, this process is easier and faster
using filter() method.
We have a function filter_vowels that checks if a letter is a vowel or not.
This function is passed onto filter() method with the list of letters.
filter() method then passes each letter to the filter_vowels() function to
check if it returns true or not. In the end, it creates an iterator of the ones
that return true (vowels).
Since the iterator doesn't store the values itself, we loop through it and print
out vowels one by one.
# random list
random_list = [1, 'a', 0, False, True, '0']
Output
Example
Filter the array, and return a new array with only the values equal to or
above 18:
def myFunc(x):
if x < 18:
return False
else:
return True
for x in adults:
print(x)
Try it Yourself »
Syntax
filter(function, iterable)
Parameter Values
Parameter Description
namedtuple()
The Python namedtuple() function returns a tuple-like object with names for each
position in the tuple. It was used to eliminate the problem of remembering the index
of each field of a tuple object in ordinary tuples.
Examples
Output:
Example
1. import collections
2. d1=collections.OrderedDict()
3. d1['A']=10
4. d1['C']=12
5. d1['B']=11
6. d1['D']=13
7.
8. for k,v in d1.items():
9. print (k,v)
Output:
A 10
C 12
B 11
D 13
defaultdict()
The Python defaultdict() is defined as a dictionary-like object. It is a subclass of the
built-in dict class. It provides all methods provided by dictionary but takes the first
argument as a default data type.
Example
Output:
0
Counter()
The Python Counter is a subclass of dictionary object which helps to count hashable
objects.
Example
Output:
deque()
The Python deque() is a double-ended queue which allows us to add and remove
elements from both the ends.
Example
Output:
Chainmap Objects
A chainmap class is used to groups multiple dictionary together to create a single
list. The linked dictionary stores in the list and it is public and can be accessed by
the map attribute. Consider the following example.
Example
Output:
UserDict Objects
The UserDict behaves as a wrapper around the dictionary objects. The dictionary can
be accessed as an attribute by using the UserDict object. It provides the easiness
to work with the dictionary.
data - A real dictionary used to store the contents of the UserDict class.
UserList Objects
The UserList behaves as a wrapper class around the list-objects. It is useful when we
want to add new functionality to the lists. It provides the easiness to work with the
dictionary.
data - A real list is used to store the contents of the User class.
UserString Objects
The UserList behaves as a wrapper class around the list objects. The dictionary can
be accessed as an attribute by using the UserString object. It provides the easiness
to work with the dictionary.
data - A real str object is used to store the contents of the UserString class.
math.log()
This method returns the natural logarithm of a given number. It is calculated to the
base e.
Example
1. import math
2. number = 2e-7 # small value of of x
3. print('log(fabs(x), base) is :', math.log(math.fabs(number), 10))
Output:
math.log10()
This method returns base 10 logarithm of the given number and called the standard
logarithm.
Example
1. import math
2. x=13 # small value of of x
3. print('log10(x) is :', math.log10(x))
Output:
log10(x) is : 1.1139433523068367
math.exp()
This method returns a floating-point number after raising e to the given number.
Example
1. import math
2. number = 5e-2 # small value of of x
3. print('The given number (x) is :', number)
4. print('e^x (using exp() function) is :', math.exp(number)-1)
Output:
math.pow(x,y)
This method returns the power of the x corresponding to the value of y. If value of x
is negative or y is not integer value than it raises a ValueError.
Example
1. import math
2. number = math.pow(10,2)
3. print("The power of number:",number)
Output:
math.floor(x)
This method returns the floor value of the x. It returns the less than or equal value
to x.
Example:
1. import math
2. number = math.floor(10.25201)
3. print("The floor value is:",number)
Output:
math.ceil(x)
This method returns the ceil value of the x. It returns the greater than or equal
value to x.
1. import math
2. number = math.ceil(10.25201)
3. print("The floor value is:",number)
Output:
1. import math
2. number = math.fabs(10.001)
3. print("The floor absolute is:",number)
Output:
math.factorial()
This method returns the factorial of the given number x. If x is not integral, it raises
a ValueError.
Example
1. import math
2. number = math.factorial(7)
3. print("The factorial of number:",number)
Output:
math.modf(x)
This method returns the fractional and integer parts of x. It carries the sign of x is
float.
Example
1. import math
2. number = math.modf(44.5)
3. print("The modf of number:",number)
Output:
Python provides the several math modules which can perform the complex task in
single-line of code. In this tutorial, we have discussed a few important math
modules.
There are different types of functions used in a random module which is given
below:
random.random()
This function generates a random float number between 0.0 and 1.0.
random.randint()
This function returns a random integer between the specified integers.
random.choice()
This function returns a randomly selected element from a non-empty sequence.
Example
Output:
random.shuffle()
This function randomly reorders the elements in the list.
random.randrange(beg,end,step)
This function is used to generate a number within the range specified in its
argument. It accepts three arguments, beginning number, last number, and step,
which is used to skip a number in the range. Consider the following example.
Output:
random.seed()
This function is used to apply on the particular random number with the seed
argument. It returns the mapper value. Consider the following example.
Output:
mean() function
The mean() function is used to calculate the arithmetic mean of the numbers in the
list.
Example
1. import statistics
2. # list of positive integer numbers
3. datasets = [5, 2, 7, 4, 2, 6, 8]
4. x = statistics.mean(datasets)
5. # Printing the mean
6. print("Mean is :", x)
Output:
median() function
The median() function is used to return the middle value of the numeric data in the
list.
Example
1. import statistics
2. datasets = [4, -5, 6, 6, 9, 4, 5, -2]
3. # Printing median of the
4. # random data-set
5. print("Median of data-set is : % s "
6. % (statistics.median(datasets)))
Output:
mode() function
The mode() function returns the most common data that occurs in the list.
Example
1. import statistics
2. # declaring a simple data-set consisting of real valued positive integers.
3. dataset =[2, 4, 7, 7, 2, 2, 3, 6, 6, 8]
4. # Printing out the mode of given data-set
5. print("Calculated Mode % s" % (statistics.mode(dataset)))
Output:
Calculated Mode 2
stdev() function
The stdev() function is used to calculate the standard deviation on a given sample
which is available in the form of the list.
Example
1. import statistics
2. # creating a simple data - set
3. sample = [7, 8, 9, 10, 11]
4. # Prints standard deviation
5. print("Standard Deviation of sample is % s "
6. % (statistics.stdev(sample)))
Output:
median_low()
The median_low function is used to return the low median of numeric data in the
list.
Example
1. import statistics
2. # simple list of a set of integers
3. set1 = [4, 6, 2, 5, 7, 7]
4. # Note: low median will always be a member of the data-set.
5. # Print low median of the data-set
6. print("Low median of data-set is % s "
7. % (statistics.median_low(set1)))
Output:
median_high()
The median_high function is used to return the high median of numeric data in the
list.
Example
1. import statistics
2. # list of set of the integers
3. dataset = [2, 1, 7, 6, 1, 9]
4. print("High median of data-set is %s "
5. % (statistics.median_high(dataset)))
Output:
High median of the data-set is 6
import thread
import time
while 1:
pass
import threading
import time
exitFlag = 0
import threading
import time
threadLock = threading.Lock()
threads = []
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
Example
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
Python Multiprocessing
In this article, we will learn how we can achieve multiprocessing using Python. We
also discuss its advanced concepts.
What is Multiprocessing?
Multiprocessing is the ability of the system to run one or more processes in parallel.
In simple words, multiprocessing uses the two or more CPU within the single
computer system. This method is also capable to allocate the tasks between more
than one process.
Processing units share the main memory and peripherals to process programs
simultaneously. Multiprocessing Application breaks into smaller parts and runs
independently. Each process is allocated to the processor by the operating system.
Python provides the built-in package called multiprocessing which supports swapping
processes. Before working with the multiprocessing, we must aware with the process
object.
Why Multiprocessing?
Multiprocessing is essential to perform the multiple tasks within the Computer
system. Suppose a computer without multiprocessing or single processor. We assign
various processes to that system at the same time.
It will then have to interrupt the previous task and move to another to keep all
processes going. It is as simple as a chef is working alone in the kitchen. He has to
do several tasks to cook food such as cutting, cleaning, cooking, kneading dough,
baking, etc.
In the multiprocessing, the CPU can assign multiple tasks at one each task has its
own processor.
Multiprocessing In Python
Python provides the multiprocessing module to perform multiple tasks within the
single system. It offers a user-friendly and intuitive API to work with the
multiprocessing.
Example -
Output:
Explanation:
In the above code, we have imported the Process class then create the Process
object within the disp() function. Then we started the process using
the start() method and completed the process with the join() method. We can also
pass the arguments in the declared function using the args keywords.
Example - 2
Output:
Explanation -
In the above example, We created the two functions - the cube() function
calculates the given number's cube, and the square() function calculates the square
of the given number.
Next, we defined the process object of the Process class that has two arguments.
The first argument is a target that represents the function to be executed, and the
second argument is args that represents the argument to be passed within the
function.
1. process1.start()
2. process2.start()
Let's see the simple example of a get number of CPUs currently in the system.
Example -
1. import multiprocessing
2. print("The number of CPU currently working in system : ", multiprocessing.cp
u_count())
Output:
The above number of CPUs can vary for your pc. For us, the number of cores is 32.
Queues are passed as a parameter in the Process' target function to allow the
process to consume data. The Queue provides the put() function to insert the data
and get() function to get data from the queues. Let's understand the following
example.
Example -
Output:
Explanation -
In the above code, we have imported the Queue class and initialized the list named
fruits. Next, we assigned a count to 1. The count variable will count the total
number of elements. Then, we created the queue object by calling
the Queue() method. This object will used to perform operations in the Queue. In
for loop, we inserted the elements one by one in the queue using the put() function
and increased the count by 1 with each iteration of loop.
Python Multiprocessing Lock Class
The multiprocessing Lock class is used to acquire a lock on the process so that we
can hold the other process to execute a similar code until the lock has been
released. The Lock class performs mainly two tasks. The first is to acquire a lock
using the acquire() function and the second is to release the lock using
the release() function.
In the following example, we will merge all the multiprocessing classes together.
Let's see the below example.
Example -
Output:
Task no 2
Task no 5
Task no 0
Task no 3
Task no 6
Task no 1
Task no 4
Task no 7
Task no 0 is done by Process-1
Task no 1 is done by Process-3
Task no 2 is done by Process-2
Task no 3 is done by Process-1
Task no 4 is done by Process-3
Task no 5 is done by Process-2
Task no 6 is done by Process-1
Task no 7 is done by Process-3
Example -
Output:
Example - 2
Output:
[1, 8, 27]
Proxy Objects
The proxy objects are referred to as shared objects which reside in a different
process. This object is also called as a proxy. Multiple proxy objects might have a
similar referent. A proxy object consists of various methods which are used to
invoked corresponding methods of its referent. Below is the example of proxy
objects.
Example -
Output:
The proxy objects are picklable so we can pass them between processes. These
objects are also used for level of control over the synchronization.
Method Description
join([timeout]) The join() method is used to block the process until the
process whose join() method is called terminates. The
timeout is optional argument.
When the server listens for the TCP connection from a client, it initiates a connection
on port 587.
Python provides a smtplib module, which defines an the SMTP client session object
used to send emails to an internet machine. For this purpose, we have to import
the smtplib module using the import statement.
1. $ import smtplib
The SMTP object is used for the email transfer. The following syntax is used to
create the smtplib object.
1. import smtplib
2. smtpObj = smtplib.SMTP(host, port, local_hostname)
o host: It is the hostname of the machine which is running your SMTP server.
Here, we can specify the IP address of the server like
(https://www.javatpoint.com) or localhost. It is an optional parameter.
o port: It is the port number on which the host machine is listening to the
SMTP connections. It is 25 by default.
o local_hostname: If the SMTP server is running on your local machine, we
can mention the hostname of the local machine.
The sendmail() method of the SMTP object is used to send the mail to the desired
machine. The syntax is given below.
Example
1. #!/usr/bin/python3
2. import smtplib
3. sender_mail = 'sender@fromdomain.com'
4. receivers_mail = ['reciever@todomain.com']
5. message = """From: From Person %s
6. To: To Person %s
7. Subject: Sending SMTP e-mail
8. This is a test e-mail message.
9. """%(sender_mail,receivers_mail)
10.try:
11. smtpObj = smtplib.SMTP('localhost')
12. smtpObj.sendmail(sender_mail, receivers_mail, message)
13. print("Successfully sent email")
14.except Exception:
15. print("Error: unable to send email")
Here, we need to login to the Gmail account using Gmail user name and password.
For this purpose, the smtplib provide the login() method, which accepts the
username and password of the sender.
This may make your Gmail ask you for access to less secure apps if you're using
Gmail. You will need to turn this ON temporarily for this to work.
Example
1. #!/usr/bin/python3
2. import smtplib
3. sender_mail = 'sender@gmail.com'
4. receivers_mail = ['reciever@gmail.com']
5. message = """From: From Person %s
6. To: To Person %s
7. Subject: Sending SMTP e-mail
8. This is a test e-mail message.
9. """%(sender_mail,receivers_mail)
10.try:
11. password = input('Enter the password');
12. smtpObj = smtplib.SMTP('gmail.com',587)
13. smtpobj.login(sender_mail,password)
14. smtpObj.sendmail(sender_mail, receivers_mail, message)
15. print("Successfully sent email")
16.except Exception:
17. print("Error: unable to send email")
Example
1. #!/usr/bin/python3
2. import smtplib
3. sender_mail = 'sender@fromdomain.com'
4. receivers_mail = ['reciever@todomain.com']
5. message = """From: From Person %s
6. To: To Person %s
7.
8. MIME-Version:1.0
9. Content-type:text/html
10.
11.
12.Subject: Sending SMTP e-mail
13.
14.<h3>Python SMTP</h3>
15.<strong>This is a test e-mail message.</strong>
16."""%(sender_mail,receivers_mail)
17.try:
18. smtpObj = smtplib.SMTP('localhost')
19. smtpObj.sendmail(sender_mail, receivers_mail, message)
20. print("Successfully sent email")
21.except Exception:
22. print("Error: unable to send email")
Excel Documents
An Excel spreadsheet document is called a workbook which is saved in a file
with .xlsx extension. The first row of the spreadsheet is mainly reserved for the
header, while the first column identifies the sampling unit. Each workbook can
contain multiple sheets that are also called a worksheets. A box at a particular
column and row is called a cell, and each cell can include a number or text value.
The grid of cells with data forms a sheet.
The active sheet is defined as a sheet in which the user is currently viewing or last
viewed before closing Excel.
Input File
Code
Explanation: In the above example, firstly, we have imported the xlrd module and
defined the location of the file. Then we have opened the workbook from the excel
file that already exists.
Example
1. Example -
2. import pandas as pd
3.
4. # Read the file
5. data = pd.read_csv(".csv", low_memory=False)
6.
7. # Output the number of rows
8. print("Total rows: {0}".format(len(data)))
9.
10.# See which headers are available
11.print(list(data))
We can also read data from the existing spreadsheet using openpyxl. It also allows
the user to perform calculations and add content that was not part of the original
dataset.
Example
1. import openpyxl
2. my_wb = openpyxl.Workbook()
3. my_sheet = my_wb.active
4. my_sheet_title = my_sheet.title
5. print("My sheet title: " + my_sheet_title)
Output:
To learn more about openpyxl, visit our complete tutorial Click Here. We have
discussed essential detail in this tutorial.
Python Write Excel File
The Python write excel file is used to perform the multiple operations on a
spreadsheet using the xlwt module. It is an ideal way to write data and format
information to files with .xls extension.
If you want to write data to any file and don't want to go through the trouble of
doing everything by yourself, then you can use a for loop to automate the whole
process a little bit.
You can easily use a for loop with the help of the range() function to help you to
print out the values of the rows that have values in column 2. If those particular
cells are empty, you will get None.
It supports features such as formatting, images, charts, page setup, auto filters,
conditional formatting, and many others.
Pandas have excellent methods for reading all kinds of data from excel files. We can
also import the results back to pandas.
It allows us to specify the delimiter and add dest_delimiter argument. You can pass
the symbol that you want to use as a delimiter in-between " ".
Code
Output:
1. import re
Regex Functions
The following regex functions are used in the python.
SN Function Description
1 match This method matches the regex pattern in the string with the
optional flag. It returns true if a match is found in the string
otherwise it returns false.
4 split Returns a list in which the string has been split in each
match.
Meta-Characters
Metacharacter is a character with the specified meaning.
Special Sequences
Special sequences are the sequences containing \ followed by one of the characters.
Character Description
\A It returns a match if the specified characters are present at the
beginning of the string.
Sets
A set is a group of characters given inside a pair of square brackets. It represents
the special meaning.
SN Set Description
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.findall("How", str)
6.
7. print(matches)
8.
9. print(matches)
Output:
['How', 'How']
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(type(matches))
8.
9. print(matches) #matches is the search object
Output:
<class '_sre.SRE_Match'>
<_sre.SRE_Match object; span=(0, 3), match='How'>
1. span(): It returns the tuple containing the starting and end position of the
match.
3. group(): The part of the string is returned where the match is found.
Example
1. import re
2.
3. str = "How are you. How is everything"
4.
5. matches = re.search("How", str)
6.
7. print(matches.span())
8.
9. print(matches.group())
10.
11.print(matches.string)
Output:
(0, 3)
How
How are you. How is everything