Python Class PRG
Python Class PRG
Python Class PRG
com/tutorials/python/
https://www.educative.io/edpresso/how-is-tryexcept-used-in-python
https://realpython.com/regex-python/#quantifiers
https://www.youtube.com/watch?v=vFiBKa4VbtU
https://www.analyticsvidhya.com/blog/2015/06/regular-expression-python/
n = 10
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("SUM of first ", n, "numbers is: ", sum )
n = 10
sum = n * (n+1) / 2
average = ( n * (n+1) / 2) / n
print("Sum of fthe irst ", n, "natural numbers using formula is: ", sum )
print("Average of the first ", n, "natural numbers using formula is: ", average )
print("\n")
print("All entered numbers ", numberList)
7. Write a Python program to count the number of even and odd numbers from a series of
numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9) # Declaring the tuple
count_odd = 0
count_even = 0
for x in numbers:
if not x % 2:
count_even+=1
else:
count_odd+=1
print("Number of even numbers :",count_even)
print("Number of odd numbers :",count_odd)
8. Write a Python program that accepts a string and calculate the number of digits and letters.
s = input("Input a string")
d=l=0
for c in s:
if c.isdigit():
d=d+1
elif c.isalpha():
l=l+1
else:
pass
print("Letters", l)
print("Digits", d)
count number of vowels
string=raw_input("Enter string:")
vowels=0
for i in string:
if(i=='a' or i=='e' or i=='i' or i=='o' or i=='u' or i=='A' or i=='E' or i=='I' or i=='O' or
i=='U'):
vowels=vowels+1
print("Number of vowels are:")
print(vowels)
while loop
1.sum and average
n = 20
total_numbers = n
sum=0
while (n >= 0):
sum += n
n-=1
print ("sum using while loop ", sum)
average = sum / total_numbers
print("Average using a while loop ", average)
n=int(input("Enter number:"))
count=0
while(n>0):
count=count+1
n=n//10
print("The number of digits in the number are:",count)
Matrix Addition
matrixOne = [[6,9,11],
[2 ,3,8]]
matrixTwo = [[15,18,11],
[26,16,19]]
result = [[0,0,0],
[0,0,0]]
1. to Form a New String Made of the First 2 and Last 2 characters From a Given String
2. to Calculate the Length of a String Without Using a Library Function
note : The
else statement gets executed after the for loop execution.
However, if the loop contains the break statement, it will not execute
the else statement and also comes out of the loop.
1. Argument order
def add(num1, num2):
return num1 + num2
sum1 = add(200, 300)
sum2 = add(8, 90)
print(sum1)
print(sum2)
sum3=add(num2=300,num1=100)
print(sum3)
____________________________
def add_r(a, b):
x=a+b
return x
print (add_r(2,3))
add_n(2,3)
____________________________________________
even odd number
def evenOdd( x ):
if (x % 2 == 0):
print "even"
else:
print "odd"
L=[3,4,5,6,7]
for i in L:
evenOdd(i)
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
variable argument
def display(*name, **address):
for items in name:
print (items)
for items in address.items():
print (items)
display('john','Mary','Nina',John='LA',Mary='NY',Nina='DC')
Nested function
def Square(X):
return (X * X)
def SumofSquares(Array, n):
Sum = 0
for i in range(n):
SquaredValue = Square(Array[i])
print(Square(Array[i]))
Sum += SquaredValue
return Sum
__________________________________________________
def mul(x,y):
return x*y
def div(x,y):
return x/y
def sub(x,y):
return x-y
def add(x,y):
return x+y
age = 42
name = "Dominic"
places = ["Berlin", "Cape Town", "New York"]
def info():
print("%s is % i years old." % (name, age))
return
info()
def output():
return
place = "Berlin"
name = "Dominic"
output()
___________________________________________
call by value
def val(x):
x+=1
print(id(x))
x=10
val(x)
print(id(x))
call by reference
def val(x):
x.append(4)
print(x,id(x))
x=[1,2,3]
val(x)
print(x,id(x))
x = "global"
def foo():
global x
x = "local"
print(x)
print(x)
foo()
print(x)
print(x)
Class and object
class MyClass:
variable = "hello"
def function(self):
print("This is a message inside the class.")
my=MyClass()
my.function()
print(my.variable)
class MyClass:
variable = "hello"
def function(self):
my=MyClass()
my1=MyClass()
my.function()
print(my.variable)
print()
my.function()
print(my1.variable)
__________________________________________________________________________________
class person:
age=10
def greet(self):
print("welcome")
obj=person()
obj.greet()
print(obj.age)
__________________________________________________________________________________
class add:
a=10
b=15
def num(s):
print("sum",s.a+s.b)
obj1=add()
obj2=add()
obj1.num()
obj2.num()
__________________________________________________________________________________
class num:
a=10
b=15
def add(self):
print("sum",self.a+self.b)
def sub(self):
print("sum",self.a-self.b)
def mul(self):
print("sum",self.a*self.b)
def div(self):
print("sum",self.a/self.b)
obj1=num()
obj1.add()
obj1.sub()
obj1.mul()
obj1.div()
class cal:
return x + y
return x - y
def multiply(self,x, y):
return x * y
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
obj=cal()
while True:
if choice == '1':
break
else:
print("Invalid Input")
_________________________________________________________________________________
class Vehicle:
name = ""
kind = "car"
color = ""
value = 100.00
def description(self):
return desc_str
car1=Vehicle()
car2=Vehicle()
print(car1.description())
print(car2.description())
constructor
class num:
a=0
b=0
def si(self,a,b):
self.a = a
self.b = b
def add(self):
return(self.a+self.b)
s=num()
s.si(10,30)
print(s.add())
class num:
a=0
b=0
def __init__(self,a,b):
self.a = a
self.b = b
def add(self):
return(self.a+self.b)
s=num(10,30)
print(s.add())
class Addition:
def __init__(self):
self.first = 10
self.second = 13
def display(self):
def calculate(self):
obj = Addition()
# perform Addition
obj.calculate()
# display result
obj.display()
__________________________________________________________________________________
Constructor
class Rectangle():
self.length = l
self.width = w
def rectangle_area(self):
return self.length*self.width
print(newRectangle.rectangle_area())
__________________________________________________________________________________
class Circle():
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
class cal:
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
class check():
def __init__(self):
self.n=[]
def add(self,a):
return self.n.append(a)
def remove(self,b):
self.n.remove(b)
def dis(self):
return (self.n)
obj=check()
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Delete")
print("3. Display")
if choice==1:
obj.add(n)
print("List: ",obj.dis())
elif choice==2:
n=int(input("Enter number to remove: "))
obj.remove(n)
print("List: ",obj.dis())
elif choice==3:
print("List: ",obj.dis())
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
class std:
stream ="BCA"
self.roll=roll
A=std()
B=std()
A.set(101)
B.set(102)
print(A.stream)
print(A.roll)
print(B.stream)
print(B.roll)
_________________________________________________________________________________
class CSStudent:
stream = 'cse'
def __init__(self,name,roll):
self.name = name
self.roll = roll
# Objects of CSStudent class
a = CSStudent('jack', 1)
b = CSStudent('jill', 2)
print(a.stream)
print(b.stream)
print(a.name)
print(b.name)
print(a.roll)
print(b.roll)
print(CSStudent.stream)
inheritance
single inheritance
class Parent():
print(“first method”)
class child(parent):
def second(self):
print(“second method”)
c=child()
c.first()
c.second()
__________________________________________________________________________________
class Animal:
def eat(self):
print("Animal eating")
def sleep(self):
print("Animal is sleeping")
class Dog(Animal) :
def bark(self):
print("Dog barking")
d=Dog()
d.bark()
d.eat()
d.sleep()
_________________________________________________________________________________
class Parent:
parentname = ""
childname = ""
def show_parent(self):
print(self.parentname)
# Child class created inherits Parent class
class Child(Parent):
def show_child(self):
print(self.childname)
class Base2(object):
def __init__(self):
self.str2 = "BCA 2"
print("Base2")
Base1.__init__(self)
Base2.__init__(self)
print("Derived")
def printStrs(self):
print(self.str1, self.str2)
ob = Derived()
ob.printStrs()
Multilevel inheritance using constructor
class Base(object):
# Constructor
def __init__(self, name):
self.name = name
# To get name
def getName(self):
return self.name
class Child(Base):
# Constructor
def __init__(self, name, age):
Base.__init__(self, name)
self.age = age
# To get name
def getAge(self):
return self.age
# Constructor
def __init__(self, name, age, address):
Child.__init__(self, name, age)
self.address = address
# To get address
def getAddress(self):
return self.address
# Driver code
g = GrandChild("sjc", 132, "Bangalore")
print(g.getName(), g.getAge(), g.getAddress())
__________________________________________________________________________________
Multiple inheritance with constructor
class A:
def __init__(self):
self.name = 'John'
self.age = 23
def getName(self):
return self.name
class B:
def __init__(self):
self.name = 'Richard'
self.id = '32'
def getName(self):
return self.name
def getName(self):
return self.name
C1 = C()
print(C1.getName())
super keyword with single inheritance
class Mammal(object):
def __init__(self, mammalName):
print(mammalName, 'is a warm-blooded animal.')
class Dog(Mammal):
def __init__(self):
print('Dog has four legs.')
super().__init__('Dog')
d1 = Dog()
_________________________________________________________________________________
class A:
def __init__(self):
super().__init__()
self.name = 'John'
self.age = 23
def getName(self):
return self.name
class B:
def __init__(self):
super().__init__()
self.name = 'Richard'
self.id = '32'
def getName(self):
return self.name
def getName(self):
return self.name
C1 = C()
print(C1.getName())
class Animal:
def __init__(self, animalName):
print(animalName, 'is an animal.');
class A:
def __init__(self):
print('Initializing: class A')
def sub_method(self, b):
print('Printing from class A:', b)
class B(A):
def __init__(self):
print('Initializing: class B')
super().__init__()
class std:
def __init__(self, name):
self.Name = name
def displayAge(self):
print("Age: ", self.Name)
obj = std("jack")
obj.displayAge()
Private Access Modifier
class MyClass:
# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)
# Driver code
myObject = MyClass()
print(myObject._MyClass__hiddenVariable)
__________________________________________________________________________________
class std:
# private members
__name = None
__roll = None
__branch = None
# constructor
def __init__(self, name, roll, branch):
self.__name = name
self.__roll = roll
self.__branch = branch
# private member function
def __displayDetails(self):
# creating object
obj = Geek("jack", 17bca06256, "python ")
__________________________________________________________________________________
class Company:
# constructor
def show(self):
class Emp(Company):
# constructor
def show_sal(self):
e.show_sal()
Polymorphism
class India():
def capital(self):
print("New Delhi")
def language(self):
print("Hindi and English")
class USA():
def capital(self):
print("Washington, D.C.")
def language(self):
print("English")
obj_ind = India()
obj_usa = USA()
for country in (obj_ind, obj_usa):
country.capital()
country.language()
class Square:
side = 5
def calculate_area(self):
class Triangle:
base = 5
height = 4
def calculate_area(self):
sq = Square()
tri = Triangle()
Method Overloading
class OverloadDemo:
def add (self, *a ) :
# variable to hold sum of numbers
sum = 0
# iterate over the arguments
for num in a:
# add numbers
sum = sum + num
return sum
# create object of class
obj = OverloadDemo ()
# call method with 5 arguments
sum = obj. add(1,2,3,4,5)
print("Sum of 5 numbers is " + str(sum))
# call method with 4 arguments
sum = obj. add(1,2,3,4)
print("Sum of 4 numbers is " + str(sum))
# call method with 3 argument
sum = obj. add(1,2,3)
print("Sum of 3 numbers is " + str(sum))
# call method with 0 argument
sum = obj. add()
print("Sum of 0 numbers is " + str(sum))
method overriding
class Animal:
multicellular = True
eukaryotic = True
def breathe(self):
print("I breathe oxygen.")
def feed(self):
print("I eat food.")
class Herbivorous(Animal):
def feed(self):
print("I eat only plants. I am vegetarian.")
herbi = Herbivorous()
herbi.feed()
herbi.breathe()
__________________________________________________________________________________
class Rectangle():
def __init__(self,length,breadth):
self.length = length
self.breadth = breadth
def getArea(self):
print(self.length*self.breadth," is area of rectangle")
class Square(Rectangle):
def __init__(self,side):
self.side = side
Rectangle.__init__(self,side,side)
def getArea(self):
print(self.side*self.side," is area of square")
s = Square(4)
r = Rectangle(2,4)
s.getArea()
r.getArea()
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
print('This Department class is inherited from Employee')
class Sales(Employee):
def message(self):
print('This Sales class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
print('------------')
sl = Sales()
sl.message()
________________________________________________________________________________
how to use method overriding in Multiple inheritance
class Employee:
class Department(Employee):
emp = Employee()
emp.add(10, 20)
print('------------')
dept = Department()
dept.add(50, 130, 90)
________________________________________________________________________________
calling superclass method within the overridden method
class Employee:
def message(self):
print('This message is from Employee Class')
class Department(Employee):
def message(self):
Employee.message(self)
print('This Department class is inherited from Employee')
emp = Employee()
emp.message()
print('------------')
dept = Department()
dept.message()
Operator overloading
print(1+2)
print("a"+"b")
print(int.__add__(1,2))
print(int.__sub__(2,1))
print(str.__add__("a","b"))
a= 1
b=2
print(a+b)
print(a.__add__(b))
a = ' Python'
print(len(a))
print(a.__len__())
class int:
class str:
def __add__(self *a)
__________________________________________________________________________________
class A:
def __init__(self, a):
self.a = a
print(ob1 + ob2)
print(ob3 + ob4)
class complex:
self.a = a
self.b = b
Ob1 = complex(1, 2)
Ob2 = complex(2, 3)
print(Ob3)
class std:
def __init__(self,m1,m2):
self.m1=m1
self.m2=m2
def __add__(self,other):
m1=self.m1+other.m1
m2=self.m2+other.m2
s3=std(m1,m2)
return s3
s1=std(58,69)
s2=std(70,60)
s3=s1+s2
print(s3.m1)
print(s3.m2)
__________________________________________________________________________________
class A:
def __init__(self, a):
self.a = a
def __gt__(self, other):
if(self.a>other.a):
return True
else:
return False
ob1 = A(2)
ob2 = A(3)
if(ob1>ob2):
print("ob1 is greater than ob2")
else:
print("ob2 is greater than ob1")
overriding absolute function
class Vector:
def __init__(self, x_comp, y_comp):
self.x_comp = x_comp
self.y_comp = y_comp
def __abs__(self):
return (self.x_comp ** 2 + self.y_comp ** 2) ** 0.5
def add(self):
return (self.x_comp ** 2 + self.y_comp ** 2) ** 0.5
vector = Vector(2, 4)
print(vector.add())
print(abs(vector))
import math
class Circle:
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
def getRadius(self):
return self.__radius
def area(self):
return math.pi * self.__radius ** 2
def __str__(self):
return "Circle with radius " + str(self.__radius)
c1 = Circle(4)
print(c1.getRadius())
c2 = Circle(5)
print(c2.getRadius())
c3 = c1 + c2
print(c3.getRadius())
print( c3 > c2) # Became possible because we have added __gt__ method
print( c1 < c2) # Became possible because we have added __lt__ method
print(c3)
square = lambda x : x * x
square (5)
def square(x):
return (x * x)
x = lambda a : a + 10
print(x(5))
x = lambda a, b : a * b
print(x(5, 6))
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
__________________________________________________________________________________
class Component:
def __init__(self):
def m1(self):
print('Component class m1() method executed...')
class Composite:
def __init__(self):
self.obj1 = Component()
def m2(self):
self.obj1.m1()
obj2 = Composite()
obj2.m2()
Composition
class Salary:
def __init__(self, pay):
self.pay = pay
def get_total(self):
return (self.pay*12)
class Employee:
self.pay = pay
self.bonus = bonus
self.obj_salary = Salary(self.pay)
def annual_salary(self):
print(obj_emp.annual_salary())
_________________________________________________________________________________
aggregation
class Salary:
self.pay = pay
def get_total(self):
return (self.pay*12)
class Employee:
self.pay = pay
self.bonus = bonus
def annual_salary(self):
obj_sal = Salary(600)
print(obj_emp.annual_salary())
randomList = ['a', 0, 2]
try:
r = 1/int(entry)
break
except:
print("Next entry.")
print()
class Student:
name = 'Student'
self.a = a
self.b = b
@staticmethod
def info():
class Student:
name = 'Student'
self.a = a
self.b = b
@classmethod
def info(cls):
return cls.name
print(Student.info())
(x,y) = (5,0)
try:
z = x/y
except ZeroDivisionError as e:
z=e
print (z)
try:
l = [1, 2, 3]
l[4]
except IndexError as e:
print(e)
try:
print("The Result:",value_one/value_second)
except ZeroDivisionError:
except ValueError:
__________________________________________________________________________________
try:
x=1
y=2
print(x/y)
except TypeError:
except NameError:
print("out")
__________________________________________________________________________________
try:
x=1
y=2
print(x/y)
except (TypeError,NameError):
print("out")
try:
c = a/b
except ZeroDivisionError:
except TypeError:
except:
else:
try:
if x > 100:
raise ValueError(x)
except ValueError:
else:
x = "hello"
if not type(x) is int:
raise TypeError("Only integers are allowed")
x=1
try:
if x >10:
Ex = ValueError()
Ex.sterror = "Value must be within 1 and 10."
raise Ex
except ValueError as e:
print("ValueError Exception!", e.sterror)
try:
raise MemoryError(“memory Error”)
except MemoryError as e
print(e)
class ValueTooLargeError(Error):
"""Raised when the input value is too large"""
pass
class A(Exception)
def ___init__(self,msg)
self.msg=msg
def print(self)
try:
raise A (“Welcome”)
except A as e:
e.print()
class Invalid(Exception):
def __init__(self,msg):
self.msg=msg
l=-1
try :
if l < 1:
except invalid as e:
print(e.msg)
class SalaryNotInRangeError(Exception):
Attributes:
"""
self.salary = salary
self.message = message
super().__init__(self.message)
raise SalaryNotInRangeError(salary)
__________________________________________________________________________________
from tkinter import *
top = Tk()
top.geometry("400x250")
name = Label(top, text = "Name").place(x = 30,y = 50)
email = Label(top, text = "Email").place(x = 30, y = 90)
password = Label(top, text = "Password").place(x = 30, y = 130)
sbmitbtn = Button(top, text = "Submit",activebackground = "pink", activeforeground = "blue").place(
x = 30, y = 170)
e1 = Entry(top).place(x = 80, y = 50)
e2 = Entry(top).place(x = 80, y = 90)
e3 = Entry(top).place(x = 95, y = 130)
top.mainloop()
import tkinter as tk
from functools import partial
def call_result(label_result, n1, n2):
num1 = (n1.get())
num2 = (n2.get())
result = int(num1)+int(num2)
label_result.config(text="Result = %d" % result)
return
root = tk.Tk()
root.geometry('400x200+100+200')
root.title('Calculator')
number1 = tk.StringVar()
number2 = tk.StringVar()
labelNum1 = tk.Label(root, text="A").grid(row=1, column=0)
labelNum2 = tk.Label(root, text="B").grid(row=2, column=0)
labelResult = tk.Label(root)
labelResult.grid(row=7, column=2)
entryNum1 = tk.Entry(root, textvariable=number1).grid(row=1, column=2)
entryNum2 = tk.Entry(root, textvariable=number2).grid(row=2, column=2)
call_result = partial(call_result, labelResult, number1, number2)
buttonCal = tk.Button(root, text="Calculate", command=call_result).grid(row=3, column=0)
root.mainloop()
# Program to make a simple
import tkinter as tk
root=tk.Tk()
name=name_entry.get()
password=passw_var.get()
print("The name is : " + name)
print("The password is : " + password)
name_var.set("")
passw_var.set("")
import re
txt="12abc3;\"*erw345"
print(re.findall("\W",txt))
import re
txt="12abc5; \"*erw345"
print(re.findall("c5\Z",txt))
import re
string = '39801 356, 2102 1111'
pattern = '(\d{3}) (\d{2})'
match = re.findall(pattern, string)
print(match)
import re
txt = "Therain in Spain"
x = re.findall("\s", txt)
import re
s="sat rat mat eat"
print(re.findall("[srme]at",s))
import re
s="sat rat mat eat"
print(re.findall("[sre]a*t",s))
import re
print(re.search("n","\n"))
print(re.findall("n", r"\n\n\n"))
print(re.findall("bab","bab ab abc"))
print(re.findall(r"ab\b","bab ab abc"))
print(re.findall('[a-z]','avb bavz'))
print(re.findall('[a\-z]','avb -zavz'))
print(re.findall('[a-z][0-9]','avb bavz67'))
print(re.findall('[(+*)]','a+vb bavz*67'))
print(re.findall('[a+b*]','aaaa+vb bavz*67'))
print(re.findall('a+b*','aaaa+vb bavz*67'))
print(re.findall(r"ab\b","bab ab abc"))
print(re.findall('[a-z]','avb bavz'))
print(re.findall('a+b*','aaaa+vb bavz*67'))
_______________________________________________________
import re
print(re.search("n","\n"))
print(re.findall("\n","\n\n\n"))
print(re.findall("\n","\n"))
print(re.findall("n",r"\n\n\n"))
import re
print(re.findall("n","\\n\\n\\n"))
print(re.findall("n",r"\n\n\n"))
print(re.findall("\bab","ab ab abc"))
print(re.findall(r"\bab","ab ab babc"))
print(re.findall(r"ab\b","ab ab babc"))
print(re.search(r"ab\b","ab ab babc"))
output
print(re.findall('[a-z]','aVb Kavz'))
print(re.findall('[a\-z]','avb -zavz'))
output
print(re.findall('[a+b*]','aaaa+vb bavz*67'))
print(re.findall('a+b*','aaaa+vb bavz*67'))
output
['z6']
['+', '*']
['a', 'a', 'a', 'a', '+', 'b', 'b', 'a', '*']
['aaaa', 'a']
print(re.findall('[-z]','aVb Kavz'))
print(re.findall('[z-]','avb -zavz'))
print(re.findall('[^-z]','aVb Kavz'))
output
['z']
['-', 'z', 'z']
['a', 'V', 'b', ' ', 'K', 'a', 'v']
import re
print(result)
import re
regex = "([a-zA-Z]+) (\d+)"
print(re.search(regex, " welcome June 24"))
________________________________________________________
import re
string_one = 'file_record_transcript.pdf'
string_two = 'file_07241999.pdf'
string_three = 'testfile_fake.pdf.tmp'
pattern = '^(file.+)\.pdf$'
a = re.search(pattern, string_one)
b = re.search(pattern, string_two)
c = re.search(pattern, string_three)
print(a)
print(b)
print(c)
import re
pattern=re.compile('AV')
print result
print result2
Output:
['AV', 'AV']
['AV']
import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# empty string
replace = ''
_
result=re.split(r'i','Analytics Vidhya')
print result
Code
result=re.split(r'i','Analytics Vidhya',maxsplit=1)
print result
import re
text = '''
Ha! let me see her: out, alas! he's cold:
Her blood is settled, and her joints are stiff;
Life and these lips have long been separated:
Death lies on her like an untimely frost
Upon the sweetest flower of all the field.
'''
import re
print result
2. now to avoid it use “\w” instead of “.“.
print result
print (result)
4. Again, it is returning space as a word because “*” returns zero or more matches of pattern
to its left. Now to remove spaces we will go with “+“.
print (result)
6. If we will use “$” instead of “^”, it will return the word from the end of the string.
print (result)