Python Unit 2
Python Unit 2
Strings
Strings in python are surrounded by either single quotation marks, or double quotation
marks.
Example
print("Hello")
print('Hello')
output:
Hello
Hello
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
Example
Example
Note: in the result, the line breaks are inserted at the same position as in the code.
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.
Example
Get the character at position 1 (remember that the first character has the position 0):
a = "Hello, World!"
print(a[1])
output:
Since strings are arrays, we can loop through the characters in a string, with a for loop.
Example
for x in"banana":
print(x)
output :
b
a
n
a
n
a
String Length
Example
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
output :
True
Example
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
output :
True
Example
output :
Slicing
Specify the start index and the end index, separated by a colon, to return a part of the string.
Example
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
b = "Hello, World!"
print(b[:5])
output :
Hello
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
Example
a = "Hello"
b = "World"
c=a+b
print(c)
output :
HelloWorld
Example
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
find() Searches the string for a specified value and returns the position of where it wa
index() Searches the string for a specified value and returns the position of where it wa
isalpha() Returns True if all characters in the string are in the alphabet
islower() Returns True if all characters in the string are lower case
isupper() Returns True if all characters in the string are upper case
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
split() Splits the string at the specified separator, and returns a list
startswith() Returns true if the string starts with the specified value
swapcase() Swaps cases, lower case becomes upper case and vice versa
zfill() Fills the string with a specified number of 0 values at the beginning
Number System
Base or Radix: Number of elements present in the number is called Base of Radix
Types
A collection of numbers 0 and 1 together with operations is called Binary Number System.
Example
1 1 11 1011 21 10101
2 10 12 1100 22 10110
3 11 13 1101 23 10111
Example
Example
Example
Methods or techniques which can be used to convert numbers from one base to another are
called conversion. The possible conversions are,
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
Each digit of given Binary number is multiplied by their positional weight and adding
it.
Example
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
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
Step 1: Multiply each digit in the number with 8n-1,when the digit is in the nth position.
Step 3: The resultant is the equivalent decimal to the given octal number.
Step 5: Multiply each digit after decimal with`1/8^m` ,when the digit is the mth position.
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
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:
1792 10 = 111000000002
Decimal to Octal
1792 10 = 3400 8
Decimal to Hexadecimal
1792 10 = 700 16
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.
↓ ↓ ↓ ↓
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.
Hexadecimal = A 2 D E
Binary = 1010 0010 1101 1110 = 1010001011011110
A2DE16= 1213368
Hexadecimal to Decimal
Each digit of given hexadecimal number is multiplied by their positional weight and
adding it.
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
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
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.
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.
"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
To open a file for reading it is enough to specify the name of the file:
f = open("demofile.txt")
f = open("demofile.txt", "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:
demofile.txt
The open() function returns a file object, which has a read() method for reading the content
of the file:
Example
f = open("demofile.txt", "r")
print(f.read())
output :
If the file is located in a different location, you will have to specify the file path, like this:
Example
f = open("D:\\myfiles\welcome.txt", "r")
print(f.read())
Output:
By default the read() method returns the whole text, but you can also specify how many
characters you want to return:
Example
f = open("demofile.txt", "r")
print(f.read(5))
Output :
Read Lines
Example
f = open("demofile.txt", "r")
print(f.readline())
Output:
By calling readline() two times, you can read the two first lines:
Example
f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())
Output:
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("demofile.txt", "r")
for x in f:
print(x)
Output:
Close Files
It is a good practice to always close the file when you are done with it.
Example
f = open("demofile.txt", "r")
print(f.readline())
f.close()
Output:
To write to an existing file, you must add a parameter to the open() function:
Example1
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
Example2
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
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
f = open("myfile.txt", "x")
Example
f = open("myfile.txt", "w")
To delete a file, you must import the OS module, and run its os.remove() function:
Example
import os
os.remove("demofile.txt")
To avoid getting an error, you might want to check if the file exists before you try to delete
it:
Example
import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
Delete Folder
Example
import os
os.rmdir("myfolder")