Python Programming

Please leave a remark at the bottom of each page with your useful suggestion.


Table of Contents

  1. Python Introduction
  2. Python Startup
  3. Python Examples Program Collection 1
  4. Python Examples Program Collection 2
  5. Python Examples Program Collection 3
  6. Python Examples Program Collection 4
  7. Python Examples Program Collection 5
  8. Python Examples Program Collection 6
  9. Python Examples Program Collection 7
  10. Python Examples Program Collection 8

Python String rfind()

Example 1: rfind() With No start and end Argument

quote = 'Let it be, let it be, let it be'
result = quote.rfind('let it')
print("Substring 'let it':", result)
result = quote.rfind('small')
print("Substring 'small ':", result)
result = quote.rfind('be,')
if  (result != -1):
  print("Highest index where 'be,' occurs:", result)
else:
  print("Doesn't contain substring")

Python String rfind()

Example 2: rfind() With start and end Arguments

quote = 'Do small things with great love'
# Substring is searched in 'hings with great love'
print(quote.rfind('things', 10))
# Substring is searched in ' small things with great love' 
print(quote.rfind('t', 2))
# Substring is searched in 'hings with great lov'
print(quote.rfind('o small ', 10, -1))
# Substring is searched in 'll things with'
print(quote.rfind('th', 6, 20))

Python String rindex()

Example 1: rindex() With No start and end Argument

quote = 'Let it be, let it be, let it be'
result = quote.rindex('let it')
print("Substring 'let it':", result)
  
result = quote.rindex('small')
print("Substring 'small ':", result)

Python String rindex()

Example 2: rindex() With start and end Arguments

quote = 'Do small things with great love'
# Substring is searched in ' small things with great love' 
print(quote.rindex('t', 2))
# Substring is searched in 'll things with'
print(quote.rindex('th', 6, 20))
# Substring is searched in 'hings with great lov'
print(quote.rindex('o small ', 10, -1))

Python String rjust()

Example 1: Right justify string of minimum width

# example string
string = 'cat'
width = 5
# print right justified string
print(string.rjust(width))

Python String rjust()

Example 2: Right justify string and fill the remaining spaces

# example string
string = 'cat'
width = 5
fillchar = '*'
# print right justified string
print(string.rjust(width, fillchar))

Python round()

number = 13.46
# round 13.46 to the nearest integer rounded_number = round(number)
print(rounded_number) # Output: 13

Python round()

Example 1: How round() works in Python?

# for integers
print(round(10))
# for floating point
print(round(10.7))
# even choice
print(round(5.5))

Python round()

Example 2: Round a number to the given number of decimal places

print(round(2.665, 2))
print(round(2.675, 2))

Python String rpartition()

Example: How rpartition() works?

string = "Python is fun"
# 'is' separator is found
print(string.rpartition('is '))
# 'not' separator is not found
print(string.rpartition('not '))
string = "Python is fun, isn't it"
# splits at last occurence of 'is'
print(string.rpartition('is'))

Python String rsplit()

Example 1: How rsplit() works in Python?

text= 'Love thy neighbor'
# splits at space
print(text.rsplit())
grocery = 'Milk, Chicken, Bread'
# splits at ','
print(grocery.rsplit(', '))
# Splitting at ':'
print(grocery.rsplit(':'))

Python String rsplit()

Example 2: How split() works when maxsplit is specified?

grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.rsplit(', ', 2))
# maxsplit: 1
print(grocery.rsplit(', ', 1))
# maxsplit: 5
print(grocery.rsplit(', ', 5))
# maxsplit: 0
print(grocery.rsplit(', ', 0))

Python String rstrip()

title = 'Python Programming   '
# remove trailing whitespace from title result = title.rstrip() print(result)
# Output: Python Programming

Python String rstrip()

Example: Working of rstrip()

random_string = 'this is good    '
# Trailing whitespace are removed
print(random_string.rstrip())
# 'si oo' are not trailing characters so nothing is removed
print(random_string.rstrip('si oo'))
# in 'sid oo', 'd oo' are the trailing characters, 'ood' is removed from the string
print(random_string.rstrip('sid oo')) website = 'www.programiz.com/' 
print(website.rstrip('m/.'))


Python setattr()

class Student:
  marks = 88
  name = 'Sheeran'
person = Student()
# set value of name to Adam setattr(person, 'name', 'Adam')
print(person.name)
# set value of marks to 78 setattr(person, 'marks', 78)
print(person.marks) # Output: Adam # 78

Python setattr()

Example 1: How setattr() works in Python?

class Person:
    name = 'Adam'
    
p = Person()
print('Before modification:', p.name)
# setting name to 'John' setattr(p, 'name', 'John')
print('After modification:', p.name)

Python Dictionary setdefault()

Example 1: How setdefault() works when key is in the dictionary?

person = {'name': 'Phill', 'age': 22}
age = person.setdefault('age')
print('person = ',person)
print('Age = ',age)

Python Dictionary setdefault()

Example 2: How setdefault() works when key is not in the dictionary?

person = {'name': 'Phill'}
# key is not in the dictionary
salary = person.setdefault('salary')
print('person = ',person)
print('salary = ',salary)
# key is not in the dictionary
# default_value is provided
age = person.setdefault('age', 22)
print('person = ',person)
print('age = ',age)

Python slice()

text = 'Python Programing'
# get slice object to slice Python sliced_text = slice(6)
print(text[sliced_text]) # Output: Python

Python slice()

Example 1: Create a slice object for slicing

# contains indices (0, 1, 2)
result1 = slice(3)
print(result1)
# contains indices (1, 3)
result2 = slice(1, 5, 2)
print(slice(1, 5, 2))

Python slice()

Example 2: Get substring using slice object

# Program to get a substring from the given string 
py_string = 'Python'
# stop = 3
# contains 0, 1 and 2 indices
slice_object = slice(3)
print(py_string[slice_object]) # Pyt # start = 1, stop = 6, step = 2 # contains 1, 3 and 5 indices slice_object = slice(1, 6, 2) print(py_string[slice_object]) # yhn

Python slice()

Example 3: Get substring using negative index

py_string = 'Python'
# start = -1, stop = -4, step = -1
# contains indices -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_string[slice_object]) # noh

Python slice()

Example 4: Get sublist and sub-tuple

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices 0, 1 and 2
slice_object = slice(3)
print(py_list[slice_object]) # ['P', 'y', 't'] # contains indices 1 and 3
slice_object = slice(1, 5, 2)
print(py_tuple[slice_object]) # ('y', 'h')

Python slice()

Example 5: Get sublist and sub-tuple using negative index

py_list = ['P', 'y', 't', 'h', 'o', 'n']
py_tuple = ('P', 'y', 't', 'h', 'o', 'n')
# contains indices -1, -2 and -3
slice_object = slice(-1, -4, -1)
print(py_list[slice_object]) # ['n', 'o', 'h'] # contains indices -1 and -3
slice_object = slice(-1, -5, -2)
print(py_tuple[slice_object]) # ('n', 'h')

Python List sort()

prime_numbers = [11, 3, 7, 5, 2]
# sorting the list in ascending order prime_numbers.sort()
print(prime_numbers) # Output: [2, 3, 5, 7, 11]

Python List sort()

Example 1: Sort a given list

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels vowels.sort()
# print vowels print('Sorted list:', vowels)

Python List sort()

Example 2: Sort the list in Descending order

# vowels list
vowels = ['e', 'a', 'u', 'o', 'i']
# sort the vowels vowels.sort(reverse=True)
# print vowels print('Sorted list (in Descending):', vowels)

Python List sort()

Example 3: Sort the list using key

# take second element for sort
def takeSecond(elem):
    return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key random.sort(key=takeSecond)
# print list print('Sorted list:', random)

Python sorted()

numbers = [4, 2, 12, 8]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # Output: [2, 4, 8, 12]

Python sorted()

Example 1: Sort string, list, and tuple

# vowels list
py_list = ['e', 'a', 'u', 'o', 'i']
print(sorted(py_list))
# string py_string = 'Python'
print(sorted(py_string))
# vowels tuple py_tuple = ('e', 'a', 'u', 'o', 'i')
print(sorted(py_tuple))

Python sorted()

Example 3: Sort the list using sorted() having a key function

# take the second element for sort
def take_second(elem):
    return elem[1]
# random list
random = [(2, 2), (3, 4), (4, 1), (1, 3)]
# sort list with key
sorted_list = sorted(random, key=take_second)
# print list print('Sorted list:', sorted_list)

Python String split()

text = 'Python is a fun programming language'
# split the text from space print(text.split(' '))
# Output: ['Python', 'is', 'a', 'fun', 'programming', 'language']

Python String split()

Example 1: How split() works in Python?

text= 'Love thy neighbor'
# splits at space
print(text.split())
grocery = 'Milk, Chicken, Bread' # splits at ','
print(grocery.split(', '))
# Splits at ':' print(grocery.split(':'))

Python String split()

Example 2: How split() works when maxsplit is specified?

grocery = 'Milk, Chicken, Bread, Butter'
# maxsplit: 2
print(grocery.split(', ', 2))
# maxsplit: 1 print(grocery.split(', ', 1)) # maxsplit: 5
print(grocery.split(', ', 5))
# maxsplit: 0 print(grocery.split(', ', 0))

Python String splitlines()

# \n is a line boundary 
sentence = 'I\nlove\nPython\nProgramming.'
# returns a list after spliting string at line breaks resulting_list = sentence.splitlines()
print(resulting_list) # Output: ['I', 'love', 'Python', 'Programming.']

Python String splitlines()

Example 1: Python String splitlines()

# '\n' is a line break 
grocery = 'Milk\nChicken\nBread\rButter'
# returns a list after splitting the grocery string print(grocery.splitlines())

Python String splitlines()

Example 3: Passing Boolean Value in splitlines()

grocery = 'Milk\nChicken\nBread\rButter'
# returns a list including line breaks resulting_list1 = grocery.splitlines(True)
print(resulting_list1)
# returns a list without including line breaks resulting_list2 = grocery.splitlines(False)
print(resulting_list2)

Python String startswith()

message = 'Python is fun'
# check if the message starts with Python print(message.startswith('Python'))
# Output: True

Python String startswith()

Example 1: startswith() Without start and end Parameters

text = "Python is easy to learn."
result = text.startswith('is easy')
# returns False print(result)
result = text.startswith('Python is ')
# returns True print(result)
result = text.startswith('Python is easy to learn.')
# returns True print(result)

Python String startswith()

Example 2: startswith() With start and end Parameters

text = "Python programming is easy."
# start parameter: 7
# 'programming is easy.' string is searched
result = text.startswith('programming is', 7)
print(result) # start: 7, end: 18 # 'programming' string is searched
result = text.startswith('programming is', 7, 18)
print(result)
result = text.startswith('program', 7, 18)
print(result)

Python String startswith()

Example 3: startswith() With Tuple Prefix

text = "programming is easy"
result = text.startswith(('python', 'programming'))
# prints True print(result)
result = text.startswith(('is', 'easy', 'java'))
# prints False print(result) # With start and end parameter # 'is easy' string is checked
result = text.startswith(('programming', 'easy'), 12, 19)
# prints False print(result)

Python staticmethod()

class Calculator:
  def add_numbers(num1, num2):
    return num1 + num2
# convert add_numbers() to static method Calculator.add_numbers = staticmethod(Calculator.add_numbers)
sum = Calculator.add_numbers(5, 7) print('Sum:', sum) # Output: Sum: 12

Python staticmethod()

Example 1: Create a static method using staticmethod()

class Mathematics:
    def addNumbers(x, y):
        return x + y
# create addNumbers static method Mathematics.addNumbers = staticmethod(Mathematics.addNumbers)
print('The sum is:', Mathematics.addNumbers(5, 10))

Python staticmethod()

Example 2: Create a utility function as a static method

class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date
@staticmethod def toDashDate(date): return date.replace("/", "-")
date = Dates("15-12-2016") dateFromDB = "15/12/2016" dateWithDash = Dates.toDashDate(dateFromDB) if(date.getDate() == dateWithDash): print("Equal") else: print("Unequal")

Python staticmethod()

Example 3: How inheritance works with static method?

class Dates:
    def __init__(self, date):
        self.date = date
        
    def getDate(self):
        return self.date
@staticmethod def toDashDate(date): return date.replace("/", "-")
class DatesWithSlashes(Dates): def getDate(self): return Dates.toDashDate(self.date) date = Dates("15-12-2016") dateFromDB = DatesWithSlashes("15/12/2016") if(date.getDate() == dateFromDB.getDate()): print("Equal") else: print("Unequal")

Python str()

# string representation of Adam
print(str('Adam'))
# Output:  Adam

Python str()

Example 1: Python() String

# string representation of Luke name = str('Luke')
print(name)
# string representation of an integer 40 age = str(40)
print(age)
# string representation of a numeric string 7ft height = str('7ft')
print(height)

Python String strip()

message = '     Learn Python  '
# remove leading and trailing whitespaces print('Message:', message.strip())
# Output: Message: Learn Python

Python String strip()

Example: Working of the strip() method

string = '  xoxo love xoxo   '
# Leading and trailing whitespaces are removed
print(string.strip())
# All <whitespace>,x,o,e characters in the left # and right of string are removed
print(string.strip(' xoe'))
# Argument doesn't contain space # No characters are removed. print(string.strip('stx')) string = 'android is awesome'
print(string.strip('an'))

Python sum()

marks = [65, 71, 68, 74, 61]
# find sum of all marks total_marks = sum(marks)
print(total_marks) # Output: 339

Python sum()

Example: Working of Python sum()

numbers = [2.5, 3, 4, -5]
# start parameter is not provided
numbers_sum = sum(numbers)
print(numbers_sum) # start = 10
numbers_sum = sum(numbers, 10)
print(numbers_sum)

Python super()

class Animal(object):
  def __init__(self, animal_type):
    print('Animal Type:', animal_type)
    
class Mammal(Animal):
  def __init__(self):
# call superclass super().__init__('Mammal')
print('Mammals give birth directly') dog = Mammal() # Output: Animal Type: Mammal # Mammals give birth directly

Python super()

Example 2: super() with Multiple Inheritance

class Animal:
  def __init__(self, Animal):
    print(Animal, 'is an animal.');
class Mammal(Animal):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    super().__init__(mammalName)
    
class NonWingedMammal(Mammal):
  def __init__(self, NonWingedMammal):
    print(NonWingedMammal, "can't fly.")
    super().__init__(NonWingedMammal)
class NonMarineMammal(Mammal):
  def __init__(self, NonMarineMammal):
    print(NonMarineMammal, "can't swim.")
    super().__init__(NonMarineMammal)
class Dog(NonMarineMammal, NonWingedMammal):
  def __init__(self):
    print('Dog has 4 legs.');
    super().__init__('Dog')
    
d = Dog()
print('')
bat = NonMarineMammal('Bat')

Python String swapcase()

name = "JoHn CeNa"
# converts lowercase to uppercase and vice versa print(name.swapcase())
# Output: jOhN cEnA

Python String swapcase()

Example 1: Python swapcase()

sentence1 = "THIS SHOULD ALL BE LOWERCASE."
# converts uppercase to lowercase print(sentence1.swapcase())
sentence2 = "this should all be uppercase."
# converts lowercase to uppercase print(sentence2.swapcase())
sentence3 = "ThIs ShOuLd Be MiXeD cAsEd."
# converts lowercase to uppercase and vice versa print(sentence3.swapcase())

Python Set symmetric_difference()

A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
# returns all items to result variable except the items on intersection result = A.symmetric_difference(B) print(result)
# Output: {'a', 'b', 'e'}

Python Set symmetric_difference()

Example 1: Python Set symmetric_difference()

A = {'Python', 'Java', 'Go'}
B = {'Python', 'JavaScript', 'C' }
# returns the symmetric difference of A and B to result variable result = A.symmetric_difference(B)
print(result)

Python Set symmetric_difference()

Example 2: Python Set symmetric_difference()

A = {'a', 'b', 'c'}
B = {'a', 'b', 'c'}
# returns empty set result = A.symmetric_difference(B)
print(result)

Python Set symmetric_difference_update()

A = {'a', 'c', 'd'}
B = {'c', 'd', 'e' }
# updates A with the symmetric difference of A and B A.symmetric_difference_update(B)
print(A) # Output: {a, e}

Python Set symmetric_difference_update()

Example: Python Set symmetric_difference_update()

# create two sets A and B
A = {'Python', 'Java', 'Go'}
B = {'Python', 'JavaScript', 'C' }
print('Original Set A:', A)
# updates A with the symmetric difference of A and B A.symmetric_difference_update(B)
print('Updated Set A:', A)

Python timestamp to datetime and vice-versa

Example 1: Python timestamp to datetime

from datetime import datetime
timestamp = 1545730073
dt_object = datetime.fromtimestamp(timestamp)
print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))

Python String title()

Example 1: How Python title() works?

text = 'My favorite number is 25.'
print(text.title())
text = '234 k3l2 *43 fun'
print(text.title())

Python String title()

Example 2: title() with apostrophes

text = "He's an engineer, isn't he?"
print(text.title())

Python String title()

Example 3: Using Regex to Title Case String

import re
def titlecase(s):
    return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
     lambda mo: mo.group(0)[0].upper() +
     mo.group(0)[1:].lower(),
     s)
text = "He's an engineer, isn't he?"
print(titlecase(text))

Python String translate()

Example 1: Translation/Mapping using a translation table with translate()

# first string
firstString = "abc"
secondString = "ghi"
thirdString = "ab"
string = "abcdef"
print("Original string:", string)
translation = string.maketrans(firstString, secondString, thirdString)
# translate string
print("Translated string:", string.translate(translation))

Python String translate()

Example 2: Translation/Mapping with translate() with manual translation table

# translation table - a dictionary
translation = {97: None, 98: None, 99: 105}
string = "abcdef"
print("Original string:", string)
# translate string
print("Translated string:", string.translate(translation))

Python type()

prime_numbers = [2, 3, 5, 7]
# check type of prime_numbers result = type(prime_numbers)
print(result) # Output: <class 'list'>

Python type()

Example 1: type() with Object parameter

numbers_list = [1, 2]
print(type(numbers_list))
numbers_dict = {1: 'one', 2: 'two'}
print(type(numbers_dict))
class Foo: a = 0 foo = Foo()
print(type(foo))

Python type()

Example 2: type() With 3 Parameters

o1 = type('X', (object,), dict(a='Foo', b=12)) print(type(o1))
print(vars(o1)) class test: a = 'Foo' b = 12
o2 = type('Y', (test,), dict(a='Foo', b=12)) print(type(o2))
print(vars(o2))

Python Set union()

A = {2, 3, 5}
B = {1, 3, 5}
# compute union between A and B print('A U B = ', A.union(B))
# Output: A U B = {1, 2, 3, 5}

Python Set union()

Example 1: Python Set union()

A = {'a', 'c', 'd'}
B = {'c', 'd', 2 }
C = {1, 2, 3}
print('A U B =', A.union(B))
print('B U C =', B.union(C))
print('A U B U C =', A.union(B, C))
print('A.union() =', A.union())

Python Set update()

A = {'a', 'b'}
B = {1, 2, 3}
# updates A after the items of B is added to A A.update(B)
print(A) # Output: {'a', 1, 2, 'b', 3}

Python Set update()

Example 1: Python Set update()

A = {1, 3, 5}
B = {2, 4, 6}
C = {0}
print('Original A:', A)
# adds items of B and C to A and updates A A.update(B, C)
print('A after update()', A)

Python Set update()

Example 2: update() to add String and Dictionary to Set

# string
alphabet = 'odd'
# sets
number1 = {1, 3}
number2 = {2, 4}
# add elements of the string to the set number1.update(alphabet)
print('Set and strings:', number1) # dictionary key_value = {'key': 1, 'lock' : 2}
# add keys of dictionary to the set number2.update(key_value)
print('Set and dictionary keys:', number2)

Python String upper()

message = 'python is fun'
# convert message to uppercase print(message.upper())
# Output: PYTHON IS FUN

Python String upper()

Example 1: Convert a string to uppercase

# example string
string = "this should be uppercase!"
print(string.upper())
# string with numbers # all alphabets should be lowercase string = "Th!s Sh0uLd B3 uPp3rCas3!"
print(string.upper())

Python String upper()

Example 2: How upper() is used in a program?

# first string
firstString = "python is awesome!"
# second string
secondString = "PyThOn Is AwEsOmE!"
if(firstString.upper() == secondString.upper()):
print("The strings are same.") else: print("The strings are not same.")

Python Dictionary values()

marks = {'Physics':67, 'Maths':87}
print(marks.values())
# Output: dict_values([67, 87])

Python Dictionary values()

Example 1: Get all values from the dictionary

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
print(sales.values())

Python Dictionary values()

Example 2: How values() works when a dictionary is modified?

# random sales dictionary
sales = { 'apple': 2, 'orange': 3, 'grapes': 4 }
values = sales.values()
print('Original items:', values) # delete an item from dictionary
del[sales['apple']]
print('Updated items:', values)

Python vars()

# returns __dict__ of a list
print(vars(list))
# Output:
# {'__repr__': <slot wrapper '__repr__' of 'list' objects>, '__hash__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'list' objects>, ….}

Python vars()

Example: Python vars()

# vars() with no argument
print (vars())
# returns __dict__  of a dictionary object
print(vars(dict))

Python vars()

Example 2 : vars() with No __dict__ Attribute Argument

string = "Jones"
# vars() with a string
print(vars(string))

Python vars()

Example 3: vars() with a custom object

class Fruit:
  def __init__(self, apple = 5, banana = 10):
    self.apple = apple
    self.banana = banana
  
eat = Fruit()
# returns __dict__ of the eat object print(vars(eat))

Python String zfill()

Example 1: How zfill() works in Python?

text = "program is fun"
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))

Python String zfill()

Example 2: How zfill() works with Sign Prefix?

number = "-290"
print(number.zfill(8))
number = "+290"
print(number.zfill(8))
text = "--random+text"
print(text.zfill(20))

Python zip()

languages = ['Java', 'Python', 'JavaScript']
versions = [14, 3, 6]
result = zip(languages, versions)
print(list(result)) # Output: [('Java', 14), ('Python', 3), ('JavaScript', 6)]

Python zip()

Example 1: Python zip()

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
# No iterables are passed
result = zip()
# Converting iterator to list result_list = list(result) print(result_list) # Two iterables are passed
result = zip(number_list, str_list)
# Converting iterator to set result_set = set(result) print(result_set)

Python zip()

Example 2: Different number of iterable elements

numbersList = [1, 2, 3]
str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')
# Notice, the size of numbersList and numbers_tuple is different
result = zip(numbersList, numbers_tuple)
# Converting to set result_set = set(result) print(result_set)
result = zip(numbersList, str_list, numbers_tuple)
# Converting to set result_set = set(result) print(result_set)

Python zip()

Example 3: Unzipping the Value Using zip()

coordinate = ['x', 'y', 'z']
value = [3, 4, 5]
result = zip(coordinate, value)
result_list = list(result)
print(result_list)
c, v = zip(*result_list)
print('c =', c) print('v =', v)



Write Your Comments or Suggestion...