Sunday, October 27, 2019

Python Program to retrieve all words having 5 characters length.


import re
str = 'one two three four five six seven 8 9 10'
result = re.findall(r'\b\w{5}\b' , str)
print(result)


Ouptut:
['three', 'seven']

instead of using the findall() method,
if we use the search() method,
it will return the first occurrence of the result only.

Python program to retrieve all words staring with a numeric digit


import re
str = 'The meeting will be conducted 
on 1st and 21st of every month'
res = re.findall(r'\d[w]*' , str)
for word in res:
    print(word)

Output: 

1
2
1

Python program to fetch all words starting with a in a given string.

Ans:

import re
str ='an apple a day keeps the doctor awaya'
result = re.findall(r'a[\w]*' , str)

for word in result:
    print(word)

Oupput:

C:\Python_WorkSpace\TestProject\venv\Scripts\python.exe 
C:/Python_WorkSpace/TestProject/regdemo2.py
an
apple
a
ay
awaya

Saturday, October 26, 2019

Pickle in Python

What is Pickle?
Ans:
Suppose we want to store some employee data like id, name, salary in a file. This data is well structured and got different types. to store such data, we need to create a class Employee with the instance variables id, name, salary as shown here:

Class Emp:
       def __init__(self ,id, name ,salary):
              self.id = id
              self.name = name
              self.salary = salary
   
      def display(self):
             print("{:5d} {:20s} {:10.2f}".format(self.id,self.name,self.salary))

Then we create an object to this class and store actual data into that object. This object should be stored into a binary file in the form of bytes.this is called pickle or serialization.

Pickling is done using dump() method of pickle module as

pickle.dupm(object, file)

And unpicking is done using the load() method of pickle module

object = pickle.load(file)