Unit II
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
'hello' is the same as "hello".
You can display a string literal with the print() function:
Example
print("Hello")
print('Hello')
output:
Hello
Hello
Assign String to a Variable
Assigning a string to a variable is done with the variable name followed by an equal sign and
the string:
Example
a = "Hello"
print(a)
output :
Hello
Multiline Strings
You can assign a multiline string to a variable by using three quotes:
Example
You can use three double quotes:
a = """Loremipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua."""
print(a)
Or three single quotes:
Example
a = '''Loremipsum dolor sit amet,
consecteturadipiscingelit,
sed do eiusmodtemporincididunt
utlabore et dolore magna aliqua.'''
print(a)
Note: in the result, the line breaks are inserted at the same position as in the code.
Strings are Arrays
Like many other popular programming languages, strings in Python 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.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
output:
Looping Through a String
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
Loop through the letters in the word "banana":
for x in"banana":
print(x)
output :
b
a
n
a
n
a
String Length
To get the length of a string, use the len() function.
Example
The len() function returns the length of a string:
a = "Hello, World!"
print(len(a))
output :
Check String
To check if a certain phrase or character is present in a string, we can use the keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!"
print("free"in txt)
output :
True
Example
Print only if "free" is present:
txt = "The best things in life are free!"
if"free"in txt:
print("Yes, 'free' is present.")
output :
Yes, 'free' is present.
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.
Example
Check if "expensive" is NOT present in the following text:
txt = "The best things in life are free!"
print("expensive" not in txt)
output :
True
Example
print only if "expensive" is NOT present:
txt = "The best things in life are free!"
if"expensive" not in txt:
print("No, 'expensive' is NOT present.")
output :
No, 'expensive' is NOT present.
Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
Get the characters from position 2 to position 5 (not included):
b = "Hello, World!"
print(b[2:5])
output :
llo
Slice From the Start
By leaving out the start index, the range will start at the first character:
Example
Get the characters from the start to position 5 (not included):
b = "Hello, World!"
print(b[:5])
output :
Hello
Slice To the End
By leaving out the end index, the range will go to the end:
Example
Get the characters from position 2, and all the way to the end:
b = "Hello, World!"
print(b[2:])
output :
llo, World!
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
Example
Merge variable a with variable b into variable c:
a = "Hello"
b = "World"
c=a+b
print(c)
output :
HelloWorld
Example
To add a space between them, add a " ":
a = "Hello"
b = "World"
c=a+""+b
print(c)
output :
HelloWorld
String Methods
Python has a set of built-in methods that you can use on strings.
Note: All string methods returns new values. They do not change the original string.
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
count() Returns the number of times a specified value occurs in a string
encode() Returns an encoded version of the string
endswith() Returns true if the string ends with the specified value
expandtabs() Sets the tab size of the string
find() Searches the string for a specified value and returns the position of where it wa
format() Formats specified values in a string
format_map() Formats specified values in a string
index() Searches the string for a specified value and returns the position of where it wa
isalnum() Returns True if all characters in the string are alphanumeric
isalpha() Returns True if all characters in the string are in the alphabet
isdecimal() Returns True if all characters in the string are decimals
isdigit() Returns True if all characters in the string are digits
isidentifier() Returns True if the string is an identifier
islower() Returns True if all characters in the string are lower case
isnumeric() Returns True if all characters in the string are numeric
isprintable() Returns True if all characters in the string are printable
isspace() Returns True if all characters in the string are whitespaces
istitle() Returns True if the string follows the rules of a title
isupper() Returns True if all characters in the string are upper case
join() Joins the elements of an iterable to the end of the string
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
maketrans() Returns a translation table to be used in translations
partition() Returns a tuple where the string is parted into three parts
replace() Returns a string where a specified value is replaced with a specified value
rfind() Searches the string for a specified value and returns the last position of where
rindex() Searches the string for a specified value and returns the last position of where
rjust() Returns a right justified version of the string
rpartition() Returns a tuple where the string is parted into three parts
rsplit() Splits the string at the specified separator, and returns a list
rstrip() Returns a right trim version of the string
split() Splits the string at the specified separator, and returns a list
splitlines() Splits the string at line breaks and returns a list
startswith() Returns true if the string starts with the specified value
strip() Returns a trimmed version of the string
swapcase() Swaps cases, lower case becomes upper case and vice versa
title() Converts the first character of each word to upper case
translate() Returns a translated string
upper() Converts a string into upper case
zfill() Fills the string with a specified number of 0 values at the beginning
Number System
A collection of things together with operations is called System.
A collection of numbers together with operations is called Number System.
Number systems are the technique to represent numbers in the computer system
Base or Radix: Number of elements present in the number is called Base of Radix
Types
Binary number system
Octal number system
Decimal number system
Hexadecimal (hex) number system
Binary Number System
A collection of numbers 0 and 1 together with operations is called Binary Number System.
Characteristics of binary number system :
Uses two digits, 0 and 1.
Base or Radix = 2 (Number of elements present in the number is called Base of
Radix)
Each position in a binary number represents a 0 power of the base (2). Example 20
Last position in a binary number represents a x power of the base (2). Example 2 x
where x represents the last position - 1.
Example
Binary Number : 101012
Binary Numbers Table
Some of the binary notations of lists of decimal numbers from 1 to 30, are mentioned in the below list.
Number Binary Number Number Binary Number Number Binary Number
1 1 11 1011 21 10101
2 10 12 1100 22 10110
3 11 13 1101 23 10111
4 100 14 1110 24 11000
5 101 15 1111 25 11001
6 110 16 10000 26 11010
7 111 17 10001 27 11011
8 1000 18 10010 28 11100
9 1001 19 10011 29 11101
10 1010 20 10100 30 11110
Octal Number System
A collection of 8 numbers 0 to 7 together with operations is called Octal Number System.
Characteristics of octal number system
Uses eight digits, 0,1,2,3,4,5,6,7.
Base or Radix = 8 (Number of elements present in the number is called Base of
Radix)
Each position in an octal number represents a 0 power of the base (8). Example 80
Last position in an octal number represents a x power of the base (8). Example 8 x
where x represents the last position - 1.
Example
Octal Number : 125708
Decimal Number System
A collection of 10 numbers 0 to 9 together with operations is called Decimal Number
System.
Characteristics of decimal number system
Uses eight digits, 0,1,2,3,4,5,6,7,8,9.
Base or Radix = 10 (Number of elements present in the number is called Base of
Radix)
Each position in an octal number represents a 0 power of the base (10). Example 100
Last position in an octal number represents a x power of the base (10). Example 10 x
where x represents the last position - 1.
Example
Octal Number : 1257010
Hexadecimal Number System
A collection of 16 numbers 0 to 9, A,B,.. F together with operations is called Octal Number
System.
Characteristics of hexadecimal number system
Uses 10 digits and 6 letters, 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F. ( A = 10. B = 11, C = 12,
D = 13, E = 14, F = 15)
Base or Radix = 16 (Number of elements present in the number is called Base of
Radix)
Each position in a hexadecimal number represents a 0 power of the base (16).
Example 160
Last position in a hexadecimal number represents a x power of the base (16). Example
16x where x represents the last position - 1.
Example
Hexadecimal Number : 19FDE16
NUMBER SYSTEM – CONVERSION.
Methods or techniques which can be used to convert numbers from one base to another are
called conversion. The possible conversions are,
1. Binary to Octal, Decimal, Hexa decimal
2. Octal to Binary, Decimal, Hexa decimal
3. Decimal to Binary, Octal, Hexa Decimal
4. Hexa decimal to Binary, Octal, Decimal
Binary to Other Number system conversion
Binary to Octal conversion.
Step 1 − Divide the binary digits into groups of three (starting from the right).
Step 2 − Convert each group of three binary digits to one octal digit.
Example
Binary Number − 101012
Calculating Octal Equivalent −
Step Binary Number Octal Number
Step 1 101012 010 101
Step 2 101012 28 58
Step 3 101012 258
Binary Number − 101012= Octal Number − 258
Binary to Decimal conversion.
Each digit of given Binary number is multiplied by their positional weight and adding
it.
Example
101012 = 10101B = 1×24+0×23+1×22+0×21+1×20 = 16+4+1= 21
101112 = 10111B = 1×24+0×23+1×22+1×21+1×20 = 16+4+2+1= 23
1000112 = 100011B = 1×25+0×24+0×23+0×22+1×21+1×20 =32+2+1= 3510
Binary to Hexadecimal conversion
Step 1 − Divide the binary digits into groups of four (starting from the right).
Step 2 − Convert each group of four binary digits to one hexadecimal symbol.
Example
Binary Number − 101012
Calculating hexadecimal Equivalent −
Step Binary Number Hexadecimal Number
Step 1 101012 0001 0101
Step 2 101012 110 510
Step 3 101012 1516
Binary Number − 101012 = Hexadecimal Number − 1516
Octal Numeral System to other number system conversion
Octal to Binary conversion
Step 1 − Convert each octal digit to a 3 digit binary number (the octal digits may be
treated as decimal for this conversion).
Step 2 − Combine all the resulting binary groups (of 3 digits each) into a single binary
number.
Example
Octal Number − 258
Calculating Binary Equivalent −
Step Octal Number Binary Number
Step 258 210 510
Step 2 258 0102 1012
Step 3 258 0101012
Octal Number − 258= Binary Number − 101012
Octal to Decimal conversion
Step 1: Multiply each digit in the number with 8n-1,when the digit is in the nth position.
Step 2: Add all digits after multiplication.
Step 3: The resultant is the equivalent decimal to the given octal number.
If octal number contains a decimal point
Step 4: Let m digits are there after the decimal
Step 5: Multiply each digit after decimal with`1/8^m` ,when the digit is the mth position.
Example: Convert 6.18 to decimal number
The given number is 6.18
6.18 = (6 * 80) + (1 * `1/8`
= 6 * 1 + `1/8`
= 6 + `1/8`
= 6 + 0.125
= 6.125
The equivalent decimal number for 6.1 8 is 6.125
6.18 = 6.125
Octal to Hexa decimal conversion
Step 1: Write 3 digit binary equivalents for each digit of a given octal number.
Step 2: after, grouping each 4 digits of a binary equivalent of given number from right to
left. If factional part is appears, same procedure applied for fractional part from left to right
Step 3: Write the hexa decimal equivalent of each group.
Decimal Numeral System to other number system conversion
A repeated division and remainder algorithm can convert decimal to binary, octal, or
hexadecimal.
1. Divide the decimal number by the desired target radix (2, 8, or 16).
2. Append the remainder as the next most significant digit.
3. Repeat until the decimal number has reached zero.
Decimal to Binary
Example : convert 1792 decimal to binary:
Decimal Number Operation Quotient Remainder
1792 ÷2= 896 0
896 ÷2= 448 0
448 ÷2= 224 0
224 ÷2= 112 0
112 ÷2= 56 0
56 ÷2= 28 0
28 ÷2= 14 0
14 ÷2= 7 0
7 ÷2= 3 1
3 ÷2= 1 1
1 ÷2= 0 1
0 done.
1792 10 = 111000000002
Decimal to Octal
Example :Convert 1792 decimal to octal:
Decimal Number Operation Quotient Remainder Octal Result
1792 ÷8= 224 0 0
224 ÷8= 28 0 00
28 ÷8= 3 4 400
3 ÷8= 0 3 3400
0 done.
1792 10 = 3400 8
Decimal to Hexadecimal
Example: Convert 1792 decimal to hexadecimal:
Decimal Number Operation Quotient Remainder Hexadecimal Result
1792 ÷ 16 = 112 0 0
112 ÷ 16 = 7 0 00
7 ÷ 16 = 0 7 700
0 done.
1792 10 = 700 16
Hexadecimal Numeral System to other number system conversion
Hexa Decimal to binary conversion:
1. We write four-bit binary number for each digit of a given hexa decimal number.
2. At the end, the four-bit binary numbers are combined to form the single binary number
equivalent to the given hexadecimal number.
Example:Convert hexadecimal number (FA98)16 to binary number (?)2
Write down the four-bit binary numbers below each hexadecimal digit as shown below:
Hexadecimal Number -> F A 9 8
↓ ↓ ↓ ↓
Binary Number -> 1111 1010 1001 1000
FA9816 = (1111101010011000)2
Hexadecimal to Octal
1. When converting from hexadecimal to octal, it is often easier to first convert the
hexadecimal number into binary.
2. After it is grouped every 3 digits from right to left. Fractional part is grouped into left
to right.
3. Write the octal equivalent for every group.
Example: Cnvert A2DE 16 into octal:
Hexadecimal = A 2 D E
Binary = 1010 0010 1101 1110 = 1010001011011110
Binary: 1010001011011110 = 001 010 001 011 011 110
Binary = 001 010 001 011 011 110
1 2 1 3 3 6 = 121336 8
A2DE16= 1213368
Hexadecimal to Decimal
Each digit of given hexadecimal number is multiplied by their positional weight and
adding it.
Example: Convert A2DE16 in to decimal
= ((A) * 16 ) + (2 * 16 ) + ((D) * 16 ) + ((E) * 160)
3 2 1
= (10 * 163) + (2 * 162) + (13 * 161) + (14 * 160)
= (10 * 4096) + (2 * 256) + (13 * 16) + (14 * 1)
= 40960 + 512 + 208 + 14
= 4169410
A2DE16 = 4169410
Converting the Decimal Integer to Binary
The radix point splits the number into two parts; the part to the left of the radix point is
called the INTEGER. The part to the right of the radix point is the FRACTION. A number
such as 34.62510 is therefore split into 3410 (the integer), and .62510 (the fraction).
To convert the fraction, this must be MULTIPLIED by the radix (in this case 2 to convert to
binary). Notice that with each multiplication a CARRY is generated from the third column.
The Carry will be either 1 or 0 and these are written down at the left hand side of the result.
However when each result is multiplied the carry is ignored (don’t multiply the carry). Each
result is multiplied in this way until the result (ignoring the carry) is 000. Conversion is now
complete.
So 3410 = 1000102
So 0.62510 = .1012
Therefore the complete conversion shows that 34.62510 = 100010.1012
Converting Binary to Decimal
To convert from binary to decimal, write down the binary number giving each bit its correct
‘weighting’ i.e. the value of the columns, starting with a value of one for the right hand (least
significant) bit. Giving each bit twice the value of the previous bit as you move left.
Example:
To convert the binary number 010000112 to decimal. Write down the binary number and
assign a ‘weighting’ to each bit as in Table 1.2.1a
Now simply add up the values of each column containing a 1 bit, ignoring any columns
containing 0.
Applying the appropriate weighting to 01000011 gives 64 + 2 + 1 = 67
Therefore: 010000112 = 6710
Converting Hexadecimal to Decimal
A similar method can be used to quickly convert hexadecimal to decimal, using Table 1.2.1b
The hexadecimal digits are entered in the bottom row and then multiplied by the weighting
value for that column.
Adding the values for each column gives the decimal value.
Therefore: 25CB16 = 967510
Python File Handling
File handling is an important part of any web application.
Python has several functions for creating, reading, updating, and deleting files.
File Open
The key function for working with files in Python is the open() function.
The open() function takes two parameters; filename, and mode.
There are four different methods (modes) for opening a file:
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
"a" - Append - Opens a file for appending, creates the file if it does not exist
"w" - Write - Opens a file for writing, creates the file if it does not exist
"x" - Create - Creates the specified file, returns an error if the file exists
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
Syntax
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")
The code above is the same as:
f = open("[Link]", "rt")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Example:
Assume we have the following file, located in the same folder as Python:
[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
To open the file, use the built-in open() function.
The open() function returns a file object, which has a read() method for reading the content
of the file:
Example
f = open("[Link]", "r")
print([Link]())
output :
C:\Users\My Name>python demo_file_open.py
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
If the file is located in a different location, you will have to specify the file path, like this:
Example
Open a file on a different location:
f = open("D:\\myfiles\[Link]", "r")
print([Link]())
Output:
C:\Users\My Name>python demo_file_open_d.py
Welcome to this text file!
This file is located in a folder named "myfiles", on the D drive.
Good Luck!
Read Only Parts of the File
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
Return the 5 first characters of the file:
f = open("[Link]", "r")
print([Link](5))
Output :
C:\Users\My Name>python demo_file_open2.py
Hello
Read Lines
You can return one line by using the readline() method:
Example
Read one line of the file:
f = open("[Link]", "r")
print([Link]())
Output:
C:\Users\My Name>python demo_file_readline.py
Hello! Welcome to [Link]
By calling readline() two times, you can read the two first lines:
Example
Read two lines of the file:
f = open("[Link]", "r")
print([Link]())
print([Link]())
Output:
C:\Users\My Name>python demo_file_readline2.py
Hello! Welcome to [Link]
This file is for testing purposes.
By looping through the lines of the file, you can read the whole file, line by line:
Example
Loop through the file line by line:
f = open("[Link]", "r")
for x in f:
print(x)
Output:
C:\Users\My Name>python demo_file_readline3.py
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
Close Files
It is a good practice to always close the file when you are done with it.
Example
Close the file when you are finish with it:
f = open("[Link]", "r")
print([Link]())
[Link]()
Output:
C:\Users\My Name>python demo_file_close.py
Hello! Welcome to [Link]
Python File Write
Write to an Existing File
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example1
Open the file "[Link]" and append content to the file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
#open and read the file after the appending:
f = open("[Link]", "r")
print([Link]())
Output :
C:\Users\My Name>python demo_file_append.py
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!Now the file has more content!
Example2
Open the file "[Link]" and overwrite the content:
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
#open and read the file after the appending:
f = open("[Link]", "r")
print([Link]())
Output:
C:\Users\My Name>python demo_file_write.py
Woops! I have deleted the content!
Note: the "w" method will overwrite the entire file.
Create a New File
To create a new file in Python, use the open() method, with one of the following parameters:
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "[Link]":
f = open("[Link]", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("[Link]", "w")
Python Delete File
Delete a File
To delete a file, you must import the OS module, and run its [Link]() function:
Example
Remove the file "[Link]":
import os
[Link]("[Link]")
Check if File exist:
To avoid getting an error, you might want to check if the file exists before you try to delete
it:
Example
Check if file exists, then delete it:
import os
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("The file does not exist")
Delete Folder
To delete an entire folder, use the [Link]() method:
Example
Remove the folder "myfolder":
import os
[Link]("myfolder")
Note: You can only remove empty folders.