0% found this document useful (0 votes)
3 views29 pages

Python String Basics and Formatting Guide

The document provides a comprehensive overview of strings in Python, detailing their creation, access methods, slicing, and immutability. It also covers string formatting, escape sequences, and useful string operations, along with deprecated functions and string constants. Additionally, it introduces Python modules and the import statement for utilizing functions and classes from other modules.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views29 pages

Python String Basics and Formatting Guide

The document provides a comprehensive overview of strings in Python, detailing their creation, access methods, slicing, and immutability. It also covers string formatting, escape sequences, and useful string operations, along with deprecated functions and string constants. Additionally, it introduces Python modules and the import statement for utilizing functions and classes from other modules.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Python String

In Python, Strings are arrays of bytes representing Unicode characters. However, Python does not have
a character data type, a single character is simply a string with a length of 1. Square brackets can be
used to access elements of the string.

Creating a String
Strings in Python can be created using single quotes or double quotes or even triple quotes.

# Python Program for Creation of String

# Creating a String with single Quotes


String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

# Creating a String with double Quotes


String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)

# Creating a String with triple Quotes


String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)

# Creating String with triple Quotes allows multiple lines


String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)

Output:
String with the use of Single Quotes:
Welcome to the Geeks World

String with the use of Double Quotes:


I'm a Geek
String with the use of Triple Quotes:
I'm a Geek and I live in a world of "Geeks"

Creating a multiline String:


Geeks
For
Life
Accessing characters in Python
In Python, individual characters of a String can be accessed by using the method of Indexing. Indexing
allows negative address references to access characters from the back of the String, e.g. -1 refers to the
last character, -2 refers to the second last character, and so on.
While accessing an index out of the range will cause an IndexError. Only Integers are allowed to be
passed as an index, float or other types that will cause a TypeError.

# Python Program to Access characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing First character
print("\nFirst character of String is: ")
print(String1[0])
# Printing Last character
print("\nLast character of String is: ")
print(String1[-1])

Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:


S

String Slicing
To access a range of characters in the String, the method of slicing is used. Slicing in a String is done by
using a Slicing operator (colon).

# Python Program to demonstrate String slicing

# Creating a String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
# Printing 3rd to 12th character
print("\nSlicing characters from 3-12: ")
print(String1[3:12])
# Printing characters between 3rd and 2nd last character
print("\nSlicing characters between " +
"3rd and 2nd last character: ")
print(String1[3:-2])

Output:
Initial String:
GeeksForGeeks
Slicing characters from 3-12:
ksForGeek
Slicing characters between 3rd and 2nd last character:
ksForGee

Deleting/Updating from a String


In Python, Updation or deletion of characters from a String is not allowed. This will cause an error
because item assignment or item deletion from a String is not supported. Although deletion of the entire
String is possible with the use of a built-in del keyword. This is because Strings are immutable, hence
elements of a String cannot be changed once it has been assigned. Only new strings can be reassigned to
the same name.

Updation of a character:
# Python Program to Update character of a String
String1 = "Hello, I'm a Geek"
print("Initial String: ")
print(String1)
# Updating a character of the String
String1[2] = 'p'
print("\nUpdating character at 2nd Index: ")
print(String1)

Error:
Traceback (most recent call last):
File “/home/[Link]”, line 10, in
String1[2] = ‘p’
TypeError: ‘str’ object does not support item assignment

Updating Entire String:


# Python Program to Update entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)
# Updating a String
String1 = "Welcome to the Geek World"
print("\nUpdated String: ")
print(String1)

Output:
Initial String:
Hello, I'm a Geek
Updated String:
Welcome to the Geek World

Deletion of a character:
# Python Program to Delete
# characters from a String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)

# Deleting a character
# of the String
del String1[2]
print("\nDeleting character at 2nd Index: ")
print(String1)

Error:
Traceback (most recent call last):
File “/home/[Link]”, line 10, in
del String1[2]
TypeError: ‘str’ object doesn’t support item deletion

Deleting Entire String:


Deletion of the entire string is possible with the use of del keyword. Further, if we try to print the string,
this will produce an error because String is deleted and is unavailable to be printed.

# Python Program to Delete entire String

String1 = "Hello, I'm a Geek"


print("Initial String: ")
print(String1)
# Deleting a String with the use of del
del String1
print("\nDeleting entire String: ")
print(String1)
Error:
Traceback (most recent call last):
File “/home/[Link]”, line 12, in
print(String1)
NameError: name ‘String1’ is not defined

Escape Sequencing in Python


While printing Strings with single and double quotes in it causes SyntaxError because String already
contains Single and Double Quotes and hence cannot be printed with the use of either of these. Hence,
to print such a String either Triple Quotes are used or Escape sequences are used to print such Strings.
Escape sequences start with a backslash and can be interpreted differently. If single quotes are used to
represent a string, then all the single quotes present in the string must be escaped and same is done for
Double Quotes.

# Python Program for Escape Sequencing of String


# Initial String
String1 = '''I'm a "Geek"'''
print("Initial String with use of Triple Quotes: ")
print(String1)

# Escaping Single Quote


String1 = 'I\'m a "Geek"'
print("\nEscaping Single Quote: ")
print(String1)

# Escaping Double Quotes


String1 = "I'm a \"Geek\""
print("\nEscaping Double Quotes: ")
print(String1)

# Printing Paths with the use of Escape Sequences


String1 = "C:\\Python\\Geeks\\"
print("\nEscaping Backslashes: ")
print(String1)

Output:
Initial String with use of Triple Quotes:
I'm a "Geek"

Escaping Single Quote:


I'm a "Geek"

Escaping Double Quotes:


I'm a "Geek"

Escaping Backslashes:
C:\Python\Geeks\
To ignore the escape sequences in a String, r or R is used, this implies that the string is a raw string and
escape sequences inside it are to be ignored.

# Printing Geeks in HEX


String1 = "This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting in HEX with the use of Escape Sequences: ")
print(String1)
# Using raw String to ignore Escape Sequences
String1 = r"This is \x47\x65\x65\x6b\x73 in \x48\x45\x58"
print("\nPrinting Raw String in HEX Format: ")
print(String1)

Output:
Printing in HEX with the use of Escape Sequences:
This is Geeks in HEX

Printing Raw String in HEX Format:


This is \x47\x65\x65\x6b\x73 in \x48\x45\x58

Formatting of Strings
Strings in Python can be formatted with the use of format() method which is a very versatile and
powerful tool for formatting Strings. Format method in String contains curly braces {} as placeholders
which can hold arguments according to position or keyword to specify the order.

# Python Program for Formatting of Strings


# Default order
String1 = "{} {} {}".format('Geeks', 'For', 'Life')
print("Print String in default order: ")
print(String1)
# Positional Formatting
String1 = "{1} {0} {2}".format('Geeks', 'For', 'Life')
print("\nPrint String in Positional order: ")
print(String1)

# Keyword Formatting
String1 = "{l} {f} {g}".format(g='Geeks', f='For', l='Life')
print("\nPrint String in order of Keywords: ")
print(String1)

Output:
Print String in default order:
Geeks For Life

Print String in Positional order:


For Geeks Life

Print String in order of Keywords:


Life For Geeks
Integers such as Binary, hexadecimal, etc., and floats can be rounded or displayed in the exponent form
with the use of format specifiers.

# Formatting of Integers
String1 = "{0:b}".format(16)
print("\nBinary representation of 16 is ")
print(String1)

# Formatting of Floats
String1 = "{0:e}".format(165.6458)
print("\nExponent representation of 165.6458 is ")
print(String1)

# Rounding off Integers


String1 = "{0:.2f}".format(1/6)
print("\none-sixth is : ")
print(String1)

Output:
Binary representation of 16 is
10000

Exponent representation of 165.6458 is


1.656458e+02

one-sixth is :
0.17

A string can be left() or center(^) justified with the use of format specifiers, separated by a colon(:).

# String alignment
String1 = "|{:<10}|{:^10}|{:>10}|".format('Geeks', 'for', 'Geeks')
print("\nLeft, center and right alignment with Formatting: ")
print(String1)

Output:
Left, center and right alignment with Formatting:
|Geeks | for | Geeks|

Old style formatting was done without the use of format method by using % operator

# Python Program for Old Style Formatting of Integers


Integer1 = 12.3456789
print("Formatting in 3.2f format: ")
print('The value of Integer1 is %3.2f' % Integer1)
print("\nFormatting in 3.4f format: ")
print('The value of Integer1 is %3.4f' % Integer1)
Output:
Formatting in 3.2f format:
The value of Integer1 is 12.35

Formatting in 3.4f format:


The value of Integer1 is 12.3457

Useful String Operations


 Logical Operators on String
 String Formatting using %
 String Template Class
 Split a string
 Python Docstrings
 String slicing
 Find all duplicate characters in string
 Reverse string in Python
 Python program to check if a string is palindrome or not

String constants
Built-In Function Description
string.ascii_letters Concatenation of the ascii_lowercase and ascii_uppercase constants.
string.ascii_lowercase Concatenation of lowercase letters
string.ascii_uppercase Concatenation of uppercase letters
[Link] Digit in strings
[Link] Hexadigit in strings
[Link] concatenation of the strings lowercase and uppercase
[Link] A string must contain lowercase letters.
[Link] Octadigit in a string
[Link] ASCII characters having punctuation characters.
[Link] String of characters which are printable
[Link]() Returns True if string ends with given suffix otherwise returns False
[Link]() Returns True if string starts with given prefix otherwise returns False
[Link]() Returns True if all characters in string are digits, Otherwise, returns False
[Link]() Returns True if all characters in string are alphabets, Otherwise, returns False
[Link]() Returns true if all characters in a string are decimal.
[Link]() one of the string formatting methods, which allows multiple substitutions
and value formatting.
[Link] Returns the position of the first occurrence of substring in a string
[Link] A string must contain uppercase letters.
[Link] A string containing all characters that are considered whitespace.
[Link]() Method converts all uppercase characters to lowercase and vice versa
of the given string, and returns it
replace() returns a copy of the string where all occurrences of a substring is
replaced with another substring.
Deprecated string functions

Built-In Function Description


[Link] Returns true if all characters in a string are decimal
[Link] Returns true if all the characters in a given string are alphanumeric.
[Link] Returns True if the string is a title cased string
[Link] splits the string at the first occurrence of the separator and returns a tuple.
[Link] Check whether a string is a valid identifier or not.
[Link] Returns the length of the string.
[Link] Returns highest index of substring inside the string if substring is found.
[Link] Returns the highest alphabetical character in a string.
[Link] Returns the minimum alphabetical character in a string.
[Link] Returns a list of lines in the string.
[Link] Return a word with its first character capitalized.
[Link] Expand tabs in a string replacing them by one or more spaces
[Link] Return the lowest indexing a sub string.
[Link] find the highest index.
[Link] Return number of (non-overlapping) occurrences of substring sub in string
[Link] Return a copy of s, but with upper case, letters converted to lower case.
[Link] Return a list of words of string, If the optional second argument step is absent or None
[Link]() Return a list of the words of the string s, scanning s from the end.
rpartition() Method splits the given string into three parts
[Link] Return a list of the words of the string when only used with two arguments.
[Link] Concatenate a list or tuple of words with intervening occurrences of sep.
[Link]() It returns a copy of string with both leading and trailing white spaces removed
[Link] Return a copy of the string with leading white spaces removed.
[Link] Return a copy of the string with trailing white spaces removed.
[Link] Converts lower case letters to upper case and vice versa.
[Link] Translate the characters using table
[Link] lower case letters converted to upper case.
[Link] left-justify in a field of given width.
[Link] Right-justify in a field of given width.
[Link]() Center-justify in a field of given width.
string-zfill Pad a numeric string on the left with zero digits until given width is reached.
[Link] Return a copy of string s with all occurrences of substring old replaced by new.
[Link]() Returns the string in lowercase which can be used for caseless comparisons.
[Link] Encodes string into any encoding supported by Python. Default encoding is utf-8.
[Link] Returns a translation table usable for [Link]()
Python Modules
A Python module is a file containing Python definitions and statements. A module can define functions,
classes, and variables. A module can also include runnable code. Grouping related code into a module
makes the code easier to understand and use. It also makes the code logically organized.
Example: create a simple module

# A simple module, [Link]

def add(x, y):


return (x+y)

def subtract(x, y):


return (x-y)

Import Module in Python – Import statement


We can import the functions, classes defined in a module to another module using the import
statement in some other Python source file.
Syntax:

import module
When interpreter encounters an import statement, it imports module if the module is present in search
path. A search path is a list of directories that the interpreter searches for importing a module. For
example, to import the module [Link], we need to put the following command at the top of the script.
Note: This does not import the functions or classes directly instead imports the module only. To access
the functions inside the module the dot(.) operator is used.

Example: Importing modules in Python

# importing module [Link]


import calc

print([Link](10, 2))

Output:
12
The from import Statement
Python’s from statement lets you import specific attributes from a module without importing the
module as a whole.

Example: Importing specific attributes from the module


# importing sqrt() and factorial from the module math
from math import sqrt, factorial

# if we simply do "import math", then [Link](16) and [Link]() are required.


print(sqrt(16))
print(factorial(6))

Output:
4.0
720
Import all Names – From import * Statement
The * symbol used with the from import statement is used to import all the names from a module to a
current namespace.
Syntax:

from module_name import *


The use of * has its advantages and disadvantages. If you know exactly what you will be needing from
the module, it is not recommended to use *, else do so.

Example: Importing all names

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))

Output
4.0
720
Locating Modules
Whenever a module is imported in Python the interpreter looks for several locations. First, it will check
for the built-in module, if not found then it looks for a list of directories defined in the [Link]. Python
interpreter searches for the module in the following manner –
 First, it searches for the module in the current directory.
 If the module isn’t found in the current directory, Python then searches each directory in the shell
variable PYTHONPATH. The PYTHONPATH is an environment variable, consisting of a list of
directories.
 If that also fails python checks the installation-dependent list of directories configured at the time
Python is installed.
Example: Directories List for Modules

# importing sys module


import sys
# importing [Link]
print([Link])

Output:
[‘/home/nikhil/Desktop/gfg’, ‘/usr/lib/[Link]’, ‘/usr/lib/python3.8’, ‘/usr/lib/python3.8/lib-
dynload’, ”, ‘/home/nikhil/.local/lib/python3.8/site-packages’, ‘/usr/local/lib/python3.8/dist-packages’,
‘/usr/lib/python3/dist-packages’, ‘/usr/local/lib/python3.8/dist-packages/IPython/extensions’,
‘/home/nikhil/.ipython’]

Importing and renaming module


We can rename the module while importing it using the as keyword.

Example: Renaming the module

# importing sqrt() and factorial from the


# module math
import math as gfg

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print([Link](16))
print([Link](6))

Output
4.0
720
The dir() function
The dir() built-in function returns a sorted list of strings containing the names defined by a module. The
list contains the names of all the modules, variables, and functions that are defined in a module.

# Import built-in module random


import random
print(dir(random))

Output:
[‘BPF’, ‘LOG4’, ‘NV_MAGICCONST’, ‘RECIP_BPF’, ‘Random’, ‘SG_MAGICCONST’, ‘SystemRandom’,
‘TWOPI’, ‘_BuiltinMethodType’, ‘_MethodType’, ‘_Sequence’, ‘_Set’, ‘__all__’, ‘__builtins__’,
‘__cached__’, ‘__doc__’, ‘__file__’, ‘__loader__’, ‘__name__’, ‘__package__’, ‘__spec__’, ‘_acos’,
‘_bisect’, ‘_ceil’, ‘_cos’, ‘_e’, ‘_exp’, ‘_inst’, ‘_itertools’, ‘_log’, ‘_pi’, ‘_random’, ‘_sha512’, ‘_sin’, ‘_sqrt’,
‘_test’, ‘_test_generator’, ‘_urandom’, ‘_warn’, ‘betavariate’, ‘choice’, ‘choices’, ‘expovariate’,
‘gammavariate’, ‘gauss’, ‘getrandbits’, ‘getstate’, ‘lognormvariate’, ‘normalvariate’, ‘paretovariate’,
‘randint’, ‘random’, ‘randrange’, ‘sample’, ‘seed’, ‘setstate’, ‘shuffle’, ‘triangular’, ‘uniform’,
‘vonmisesvariate’, ‘weibullvariate’]

Code Snippet illustrating python built-in modules:


# importing built-in module math
import math

# using square root(sqrt) function contained in math module


print([Link](25))

# using pi function contained in math module


print([Link])

# 2 radians = 114.59 degrees


print([Link](2))

# 60 degrees = 1.04 radians


print([Link](60))

# Sine of 2 radians
print([Link](2))

# Cosine of 0.5 radians


print([Link](0.5))

# Tangent of 0.23 radians


print([Link](0.23))

# 1 * 2 * 3 * 4 = 24
print([Link](4))

# importing built in module random


import random

# printing random integer between 0 and 5


print([Link](0, 5))

# print random floating point number between 0 and 1


print([Link]())

# random number between 0 and 100


print([Link]() * 100)

List = [1, 4, True, 800, "python", 27, "hello"]

# using choice function in random module for choosing a random element from a set such as
a list
print([Link](List))
# importing built in module datetime
import datetime
from datetime import date
import time

# Returns the number of seconds since the Unix Epoch, January 1st 1970
print([Link]())

# Converts a number of seconds to a date object


print([Link](454554))

Output:
5.0
3.14159265359
114.591559026
1.0471975512
0.909297426826
0.87758256189
0.234143362351
24
3
0.401533172951
88.4917616788
True
1461425771.87
1970-01-06

Python Random Module


Python Random module is an in-built module of Python which is used to generate random numbers.
These are pseudo-random numbers means these are not truly random. This module can be used to
perform random actions such as generating random numbers, print random a value for a list or string,
etc.
Example: Printing a random value from a list

# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))

Output:
2
As stated above random module creates pseudo-random numbers. Random numbers depend on
seeding value. For example, if seeding value is 5 then output of below program will always be the same.
Example: Creating random numbers with seeding value

import random
[Link](5)
print([Link]())
print([Link]())

Output:
0.6229016948897019
0.7417869892607294
The output of the above code will always be the same. Therefore, it must not be used for encryption.
Let’s discuss some common operations performed by this module.

Creating Random Integers


[Link]() method is used to generate random integers between the given range.
Syntax :
randint(start, end)
Example: Creating random integers

# Python3 program explaining work of randint() function

# import random module


import random

# Generates a random number between a given positive range


r1 = [Link](5, 15)
print("Random number between 5 and 15 is % s" % (r1))

# Generates a random number between two given negative range


r2 = [Link](-10, -2)
print("Random number between -10 and -2 is % d" % (r2))

Output:
Random number between 5 and 15 is 7
Random number between -10 and -2 is -9
Creating Random Floats
[Link]() method is used to generate random integers between 0.0 to 1.
Syntax:
[Link]()

Example: # Python3 program to demonstrate the use of random() function .

# import random
from random import random

# Prints random item


print(random())

Output:
0.3717933555623072

Selecting Random Elements


[Link]() function is used to return a random item from a list, tuple, or string.
Syntax:
[Link](sequence)
Example: Selecting random elements from the list, string, and tuple using choice()

# import random
import random
# prints a random value from the list
list1 = [1, 2, 3, 4, 5, 6]
print([Link](list1))
# prints a random item from the string
string = "geeks"
print([Link](string))
# prints a random item from the tuple
tuple1 = (1, 2, 3, 4, 5)
print([Link](tuple1))

Output:
2
k
5
Shuffling List
[Link]() method is used to shuffle a sequence (list). Shuffling means changing the position of
the elements of the sequence. Here, the shuffling operation is inplace.
Syntax:
[Link](sequence, function)
Example: Shuffling a List

# import the random module


import random
# declare a list
sample_list = [1, 2, 3, 4, 5]
print("Original list : ")
print(sample_list)
# first shuffle
[Link](sample_list)
print("\nAfter the first shuffle : ")
print(sample_list)
# second shuffle
[Link](sample_list)
print("\nAfter the second shuffle : ")
print(sample_list)

Output:
Original list :
[1, 2, 3, 4, 5]
After the first shuffle :
[4, 3, 5, 2, 1]
After the second shuffle :
[1, 3, 4, 5, 2]

List of all the functions in Random Module


Function Name Description
seed() Initialize the random number generator
getstate() Returns an object with the current internal state of the random number generator
setstate() Used to restore the state of random number generator back to the specified state
getrandbits() Return an integer with a specified number of bits
randrange() Returns a random number within the range
randint() Returns a random integer within the range
choice() Returns a random item from a list, tuple, or string
choices() Returns multiple random elements from the list with replacement
sample() Returns a particular length list of items chosen from the sequence
random() Generate random floating numbers
uniform() Return random floating number between two numbers both inclusive
triangular() Return random floating point number within a range with a bias towards one extreme
betavariate() Return a random floating point number with beta distribution
expovariate() Return a random floating point number with exponential distribution
gammavariate() Return a random floating point number with gamma distribution
gauss() Return a random floating point number with Gaussian distribution
lognormvariate() Return a random floating point number with log-normal distribution
normalvariate() Return a random floating point number with normal distribution
vonmisesvariate() Return a random floating point number with von Mises distribution or
circular normal distribution
paretovariate() Return a random floating point number with Pareto distribution
weibullvariate() Return a random floating point number with Weibull distribution
Create and Access a Python Package
Packages are a way of structuring many packages and modules which helps in a well-organized hierarchy
of data set, making the directories and modules easy to access. Just like there are different drives and
folders in an OS to help us store files, similarly packages help us in storing other sub-packages and
modules, so that it can be used by the user when necessary.

Creating and Exploring Packages


To tell Python that a particular directory is a package, we create a file named __init__.py inside it and
then it is considered as a package and we may create other modules and sub-packages within it. This
__init__.py file can be left blank or can be coded with the initialization code for the package.

To create a package in Python, we need to follow these three simple steps:

1. First, we create a directory and give it a package name, preferably related to its operation.
2. Then we put the classes and the required functions in it.
3. Finally we create an __init__.py file inside the directory, to let Python know that the directory is a
package.

Example of Creating Package


Let’s look at this example and see how a package is created. Let’s create a package named Cars and
build three modules in it namely, Bmw, Audi and Nissan.
1. First we create a directory and name it Cars.
2. Then we need to create modules. To do this we need to create a file with the name [Link] and
create its content by putting this code into it.

# Python code to illustrate the Modules


class Bmw:
# First we create a constructor for this class and add members to it, here models
def __init__(self):
[Link] = ['i8', 'x1', 'x5', 'x6']

# A normal print function


def outModels(self):
print('These are the available models for BMW')
for model in [Link]:
print('\t%s ' % model)

3. Then we create another file with the name [Link] and add the similar type of code to it with
different members.

# Python code to illustrate the Module


class Audi:
# First we create a constructor for this class and add members to it, here models
def __init__(self):
[Link] = ['q7', 'a6', 'a8', 'a3']

# A normal print function


def outModels(self):
print('These are the available models for Audi')
for model in [Link]:
print('\t%s ' % model)

4. Then we create another file with the name [Link] and add the similar type of code to it with
different members.

# Python code to illustrate the Module


class Nissan:
# First we create a constructor for this class and add members to it, here models
def __init__(self):
[Link] = ['altima', '370z', 'cube', 'rogue']

# A normal print function


def outModels(self):
print('These are the available models for Nissan')
for model in [Link]:
print('\t%s ' % model)

5. Finally we create the __init__.py file. This file will be placed inside Cars directory and can be left
blank or we can put this initialisation code into it.

from Bmw import Bmw


from Audi import Audi
from Nissan import Nissan

6. Now, let’s use the package that we created. To do this make a [Link] file in the same directory
where Cars package is located and add the following code to it:

# Import classes from your brand new package


from Cars import Bmw
from Cars import Audi
from Cars import Nissan
# Create an object of Bmw class & call its method
ModBMW = Bmw()
[Link]()

# Create an object of Audi class & call its method


ModAudi = Audi()
[Link]()

# Create an object of Nissan class & call its method


ModNissan = Nissan()
[Link]()

7. Various ways of Accessing the Packages


8. Let’s look at this example and try to relate packages with it and how can we access it.

1. import in Packages
Suppose the cars and the brand directories are packages. For them to be a package they all must
contain __init__.py file in them, either blank or with some initialization code. Let’s assume that
all the models of the cars to be modules. Use of packages helps importing any modules,
individually or whole.
Suppose we want to get Bmw i8. The syntax for that would be:

'import' [Link].x5

While importing a package or sub packages or modules, Python searches the whole tree of
directories looking for the particular package and proceeds systematically as programmed by
the dot operator.
If any module contains a function and we want to import that. For e.g., a8 has a function
get_buy(1) and we want to import that, the syntax would be:
import [Link].a8
[Link].a8.get_buy(1)
While using just the import syntax, one must keep in mind that the last attribute must be a
subpackage or a module, it should not be any function or class name.
2. ‘from…import’ in Packages
Now, whenever we require using such function we would need to write the whole long line after
importing the parent package. To get through this in a simpler way we use ‘from’ keyword. For
this we first need to bring in the module using ‘from’ and ‘import’:
from [Link] import a8
Now we can call the function anywhere using
a8.get_buy(1)
There’s also another way which is less lengthy. We can directly import the function and use it
wherever necessary. First import it using:
from [Link].a8 import get_buy
Now call the function from anywhere:
get_buy(1)
3. ‘from…import *’ in Packages
While using the from…import syntax, we can import anything from submodules to class or
function or variable, defined in the same module. If the mentioned attribute in the import part is
not defined in the package then the compiler throws an ImportError exception.
Importing sub-modules might cause unwanted side-effects that happens while importing sub-
modules explicitly. Thus we can import various modules at a single time using * syntax. The
syntax is:

from [Link] import *


This will import everything i.e., modules, sub-modules, function, classes, from the sub-package.

Inheritance and Composition

What is Inheritance (Is-A Relation)?


It is a concept of Object-Oriented Programming. Inheritance is a mechanism that allows us to inherit all
the properties from another class. The class from which the properties and functionalities are utilized is
called the parent class (also called as Base Class). The class which uses the properties from another class
is called as Child Class (also known as Derived class). Inheritance is also called an Is-A Relation.
Inheritance – diagrammatic representation
In the figure above, classes are represented as boxes. The inheritance relationship is represented by an
arrow pointing from Derived Class(Child Class) to Base Class(Parent Class). The extends keyword
denotes that the Child Class is inherited or derived from Parent Class.

Syntax :
# Parent class
class Parent :
# Constructor
# Variables of Parent class
# Methods
...
...
# Child class inheriting Parent class
class Child(Parent) :
# constructor of child class
# variables of child class
# methods of child class
...
...
Example :

# parent class
class Parent:

# parent class method


def m1(self):
print('Parent Class Method called...')

# child class inheriting parent class


class Child(Parent):

# child class constructor


def __init__(self):
print('Child Class object created...')

# child class method


def m2(self):
print('Child Class Method called...')

# creating object of child class


obj = Child()
# calling parent class m1() method
obj.m1()
# calling child class m2() method
obj.m2()
Output
Child Class object created...
Parent Class Method called...
Child Class Method called...

What is Composition (Has-A Relation)?


It is one of the fundamental concepts of Object-Oriented Programming. In this concept, we will describe
a class that references to one or more objects of other classes as an Instance variable. Here, by using
class name or by creating object we can access the members of one class inside another class. It enables
creating complex types by combining objects of different classes. It means that a class Composite can
contain an object of another class Component. This type of relationship is known as Has-A Relation.

composition – diagrammatic representation


In the above figure Classes are represented as boxes with the class name
Composite and Component representing Has-A relation between both of them.
class A :
# variables of class A
# methods of class A
...
...
class B :
# by using "obj" we can access member's of class A.
obj = A()
# variables of class B
# methods of class B
...
...
Example :

class Component:

# composite class constructor


def __init__(self):
print('Component class object created...')

# composite class instance method


def m1(self):
print('Component class m1() method executed...')

class Composite:

# composite class constructor


def __init__(self):

# creating object of component class


self.obj1 = Component()
print('Composite class object also created...')

# composite class instance method


def m2(self):

print('Composite class m2() method executed...')


# calling m1() method of component class
self.obj1.m1()

# creating object of composite class


obj2 = Composite()

# calling m2() method of composite class


obj2.m2()

Output
Component class object created...
Composite class object also created...
Composite class m2() method executed...
Component class m1() method executed...

Explanation:
 In the above example, we created two classes Composite and Component to show the Has-A
Relation among them.
 In the Component class, we have one constructor and an instance method m1().
 Similarly, in Composite class, we have one constructor in which we created an object of Component
Class. Whenever we create an object of Composite Class, the object of the Component
class is automatically created.
 Now in m2() method of Composite class we are calling m1() method of Component Class using
instance variable obj1 in which reference of Component Class is stored.
 Now, whenever we call m2() method of Composite Class, automatically m1() method of Component
Class will be called.

Composition vs Inheritance
It’s big confusing among most of the people that both the concepts are pointing to Code
Reusability then what is the difference b/w Inheritance and Composition and when to use Inheritance
and when to use Composition?
Inheritance is used where a class wants to derive the nature of parent class and then modify or extend
the functionality of it. Inheritance will extend the functionality with extra features allows overriding of
methods, but in the case of Composition, we can only use that class we can not modify or extend the
functionality of it. It will not provide extra features. Thus, when one needs to use the class as it without
any modification, the composition is recommended and when one needs to change the behavior of the
method in another class, then inheritance is recommended.
File Handling:

Opening and Closing Files


Until now, you have been reading and writing to the standard input and output. Now, we will see how
to use actual data files.
Python provides basic functions and methods necessary to manipulate files by default. You can do most
of the file manipulation using a file object.
The open Function
Before you can read or write a file, you have to open it using Python's built-in open() function. This
function creates a file object, which would be utilized to call other support methods associated with it.
Syntax
file object = open(file_name [, access_mode][, buffering])
Here are parameter details −
 file_name − The file_name argument is a string value that contains the name of the file that you
want to access.
 access_mode − The access_mode determines the mode in which the file has to be opened, i.e.,
read, write, append, etc. A complete list of possible values is given below in the table. This is
optional parameter and the default file access mode is read (r).
 buffering − If the buffering value is set to 0, no buffering takes place. If the buffering value is 1,
line buffering is performed while accessing a file. If you specify the buffering value as an integer
greater than 1, then buffering action is performed with the indicated buffer size. If negative,
the buffer size is the system default(default behavior).
Here is a list of the different modes of opening a file −
[Link] Modes & Description
.

1 r
Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the
default mode.

2 rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file.
This is the default mode.

3 r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.

4 rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning
of the file.
5 w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a
new file for writing.

6 wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does
not exist, creates a new file for writing.

7 w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file
does not exist, creates a new file for reading and writing.

8 wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file
exists. If the file does not exist, creates a new file for reading and writing.

9 a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file
is in the append mode. If the file does not exist, it creates a new file for writing.

10 ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file
exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for
writing.

11 a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file
exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading
and writing.

12 ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the
file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new
file for reading and writing.
The file Object Attributes
Once a file is opened and you have one file object, you can get various information related to that file.
Here is a list of all attributes related to file object −
[Link]. Attribute & Description

1 [Link]
Returns true if file is closed, false otherwise.

2 [Link]
Returns access mode with which file was opened.

3 [Link]
Returns name of the file.

4 [Link]
Returns false if space explicitly required with print, true otherwise.
Example
Live Demo
#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]
print "Closed or not : ", [Link]
print "Opening mode : ", [Link]
print "Softspace flag : ", [Link]
This produces the following result −
Name of the file: [Link]
Closed or not : False
Opening mode : wb
Softspace flag : 0
The close() Method
The close() method of a file object flushes any unwritten information and closes the file object, after
which no more writing can be done.
Python automatically closes a file when the reference object of a file is reassigned to another file. It is a
good practice to use the close() method to close a file.
Syntax
[Link]()
Example
Live Demo
#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
print "Name of the file: ", [Link]

# Close opend file


[Link]()
This produces the following result −
Name of the file: [Link]
Reading and Writing Files
The file object provides a set of access methods to make our lives easier. We would see how to
use read() and write() methods to read and write files.
The write() Method
The write() method writes any string to an open file. It is important to note that Python strings can
have binary data and not just text.
The write() method does not add a newline character ('\n') to the end of the string −
Syntax
[Link](string)
Here, passed parameter is the content to be written into the opened file.
Example
#!/usr/bin/python

# Open a file
fo = open("[Link]", "wb")
[Link]( "Python is a great language.\nYeah its great!!\n")

# Close opend file


[Link]()
The above method would create [Link] file and would write given content in that file and finally it
would close that file. If you would open this file, it would have following content.
Python is a great language.
Yeah its great!!
The read() Method
The read() method reads a string from an open file. It is important to note that Python strings can have
binary data. apart from text data.
Syntax
[Link]([count])
Here, passed parameter is the number of bytes to be read from the opened file. This method starts
reading from the beginning of the file and if count is missing, then it tries to read as much as possible,
maybe until the end of file.
Example
Let's take a file [Link], which we created above.
#!/usr/bin/python

# Open a file
fo = open("[Link]", "r+")
str = [Link](10);
print "Read String is : ", str
# Close opend file
[Link]()
This produces the following result −
Read String is : Python is
File Positions
The tell() method tells you the current position within the file; in other words, the next read or write
will occur at that many bytes from the beginning of the file.
The seek(offset[, from]) method changes the current file position. The offset argument indicates the
number of bytes to be moved. The from argument specifies the reference position from where the
bytes are to be moved.
If from is set to 0, it means use the beginning of the file as the reference position and 1 means use the
current position as the reference position and if it is set to 2 then the end of the file would be taken as
the reference position.
Example
Let us take a file [Link], which we created above.
#!/usr/bin/python

# Open a file
fo = open("[Link]", "r+")
str = [Link](10)
print "Read String is : ", str

# Check current position


position = [Link]()
print "Current file position : ", position

# Reposition pointer at the beginning once again


position = [Link](0, 0);
str = [Link](10)
print "Again read String is : ", str
# Close opend file
[Link]()
This produces the following result −
Read String is : Python is
Current file position : 10
Again read String is : Python is
Renaming and Deleting Files
Python os module provides methods that help you perform file-processing operations, such as
renaming and deleting files.
To use this module you need to import it first and then you can call any related functions.
The rename() Method
The rename() method takes two arguments, the current filename and the new filename.
Syntax
[Link](current_file_name, new_file_name)
Example
Following is the example to rename an existing file [Link] −
#!/usr/bin/python
import os

# Rename a file from [Link] to [Link]


[Link]( "[Link]", "[Link]" )
The remove() Method
You can use the remove() method to delete files by supplying the name of the file to be deleted as the
argument.
Syntax
[Link](file_name)

You might also like