Strings, Files and Type Conversions
Strings, Files and Type Conversions
Type Conversion,
• Mathematical Functions,
• Random Numbers.
• Creating and Accessing Strings,
Operations on Strings, Indexing, Slicing,
String Manipulations, Pre-defined
functions on Strings.
•
• File I/O-Opening and Closing files,
• Different modes, File attributes, Read,
Write Operations, File Positions.
Renaming and Deleting Files, various
directory handling functions.
Introduction to Different Numeric Types
There are three numeric types in Python:
•int
•float
•complex
Variables of numeric types are created when you assign a value to
them
Example:
x = 1 # int
y = 2.8 # float
z = 1j # complex
Introduction to Different Numeric Types
Int
• Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length
x = 1
y = 35656222554887711
z = -3255522
print(type(x))
print(type(y))
print(type(z))
Introduction to Different Numeric Types
Float
• Float, or "floating point number" is a number, positive or negative, containing one
or more decimals.
x = 1.10
y = 1.0
z = -35.59
print(type(x))
print(type(y))
print(type(z))
x = 3+5j
y = 5j
z = -5j
print(type(x))
print(type(y))
print(type(z))
print(x) 1.0
print(y)
print(z) 2
(1+0j)
print(type(x)) <class 'float'>
print(type(y)) <class 'int'>
print(type(z))
<class 'complex'>
Mathematical Functions
• The min() and max() functions can be used to find the lowest or highest value in an iterable:
x = min(5, 10, 25)
y = max(5, 10, 25)
print(x) 5
print(y) 25
• The math.ceil() method rounds a number upwards to its nearest integer, and
the math.floor() method rounds a number downwards to its nearest integer, and returns
the result:
import math
x = math.ceil(1.4)
y = math.floor(1.4)
print(x) # returns 2
print(y) # returns 1
T Seshu Chakravarthy Department Of Computer Science and Engineering
25
Mathematical Functions
The math.fmod() method returns the remainder (modulo) of x/y.
import math
import math
print(math.pow(2, 3)) #8
import math
print (math.sqrt(9)) #3
print (math.sqrt(25))
#5
T Seshu Chakravarthy Department Of Computer Science and Engineering
Mathematical Functions
import math
import math
T= (1, 2, 3)
L = (3, 4, 5)
#Return the product of the elements
print(math.prod(T)) #6
print(math.prod(L)) #60
import random
#returns a number between 3 and 9 (both included)
print(random.randint(3, 9)) #4
import random
print(random.random()) #0.627
choice() : The choice() method returns a randomly selected element from the specified
sequence.
import random
def guess_the_number():
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)
while True:
# Get user's guess
guess = int(input("Enter your guess: "))
attempts += 1
# Check if the guess is correct
if guess == secret_number:
print(f"Congratulations! You guessed the number in {attempts} attempts.")
break
elif guess < secret_number:
print("Too low. Try again.")
else:
print("Too high. Try again.")
guess_the_number()
• a=‘hello’ b=“Python”
Example:
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"
greet = 'Hello’
print(len(greet)) # Output: 5
Example:
not in:
in:
txt = "The best things in life are
txt = "The best things in life are free!"
free!"
if "free" in txt:
if "expensive" not in txt:
print("Yes, 'free' is present.")
print("No, 'expensive' is NOT
else:
present.")
print("Yes, 'free' is not present.")
T Seshu Chakravarthy Department Of Computer Science and Engineering
Looping Through a String
• Since strings are arrays, we can loop through the characters in a string, with a for loop.
Syntax:
for variable in String:
print(variable)
Ex:
str="Python"
for i in str: P
print(i) y
t
h
o
n
name= "Havya"
count=0
for char in name:
if char== 'a':
count=count+1
print("No of a in my name is:",count)
No of a in my name is: 2
Hll I m Dvnsh
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
print(no_punct)
Output:
Hello he said and went
count():The count() method returns the number of times a specified value appears in the
string.
capitalize() :It converts the first character of a string to upper case and the rest is lower
case.
• The startswith() method returns True if the string starts with the specified value,
otherwise False.
• The endswith() method returns True if the string ends with the specified value,
otherwise False.
index():Searches the string for a specified value and returns the position of first occurrence where it was
found
• The index() method returns exception if the value is not found.
txt = "Hello, welcome to my world."
O/P: 4
x = txt.index("o")
print(x)
Ex1:
txt = "welcome to the Python Class"
x = txt.split()
print(x) O/P: ['welcome', 'to', 'the', 'Python', ‘Class']
Ex2:
• strip() removes any spaces at the beginning and at the end of the string
• lstrip() Remove spaces to the left of the string:
• rstrip() Remove spaces to the right of the string
Version-1:
ori_str = "hi this is a python class"
words= ori_str.split()
words.sort()
sor_str=" ".join(words)
Orginal: hi this is a python class
print("Orginal:",ori_str) After Sorting: a class hi is python this
print("After Sorting:",sor_str)
T Seshu Chakravarthy Department Of Computer Science and Engineering
File Handling
• A file is the collection of data stored on a disk in one unit identified by filename
Types of files
Text files Binary files
• Text files are structured as a sequence • Binary" files are any files where the format isn't made up
of lines, where each line includes a of readable characters.
sequence of characters. • Binary files can only be processed by an application that
know or understand the file’s format.
Web standards: html, xml, css, ... Common extensions that are binary file formats:
Source code: c, cpp, java, pl, php, , ... Images: jpg, png, gif, bmp, tiff, ...
Documents: txt, tex,rtf, ps, ... Videos: mp4, avi, mov, mpg, ...
Tabular data: csv, tsv, ... Audio: mp3, wav, wma, ...
Archive: zip, rar, 7z, tar, ...
Executable: exe, dll, so, class, ...
file attributes:
1.Name: File name is the name given to the file. A name is usually a string of characters.
2.Identifier: Identifier is a unique number for a file. It identifies files within the file system. It is not
readable to us, unlike file names.
3.Type: Type is another attribute of a file which specifies the type of file such as archive file (.zip),
source code file (.c, .java), .docx file, .txt file, etc.
4.Location: Specifies the location of the file on the device (The directory path). This attribute is a
pointer to a device.
5.Size: Specifies the current size of the file (in Kb, Mb, Gb, etc.) and possibly the maximum allowed
size of the file.
6.Protection: Specifies information about Access control (Permissions about Who can read, edit,
write, and execute the file.) It provides security to sensitive and private information.
7.Time, date, and user identification: This information tells us about the date and time on which
the file was created, last modified, created and modified by which user, etc.
File I/O-Opening and Closing files
• In Python, we use the open() method to open files.
• open() returns a “file handle/pointer” is a variable used to perform operations on
the file.
• A file handle or pointer denotes the position from which the file contents will be
read or written.
• When file is opened, file pointer points to the beginning of the file.
• In mode, we specify whether we want to read 'r', write 'w' or append 'a' to the
file.
Example:
f = open("demofile.txt", "r")
File I/O-Opening and Closing files
Mode Description
r Open a file for reading. (default)
Open a file for writing. Creates a new file if it does not exist or truncates
w the file if it exists.
Open a file for exclusive creation. If the file already exists, the operation
x fails.
Open a file for appending at the end of the file without overwriting it.
a Creates a new file if it does not exist.
t Open in text mode. (default)
b Open in binary mode.
+ Open a file for updating (reading and writing)
File I/O-Opening and Closing files
Syntax : filehandle.write(string);
• Here, string parameter is the content to be written into the opened
file.
Write Operations: write()
Ex: Open the file “first.txt" and overwrite the content
f = open('first.txt' , 'w')
str = "Hello Welcome to Python class" first.txt
f.write(str) Hello Welcome to Python class
f.close()
f = open('first.txt' , 'a')
str = " File Handling" first.txt
f.write(str) Hello Welcome to Python class File Handling
f.close()
Read Operations: read()
• The read() method reads a data from an open file.
• To read a file in Python, we must open the file in reading mode.
Syntax: filehandle.read([count]);
f = open( 'first.txt' , 'r’) O/P: Hello Welcome to Python class File
str1 = f.read() Handling
print(str1)
f.close()
N=2
f = open( 'crickter.txt' , 'r') O/P:
print(f.readlines()[N:]) ['Ganguly\n', 'Laxman']
f.close()
f.seek(5) Move file pointer five characters ahead from the beginning of a file.
f.seek(0, 2) Move file pointer to the end of a File
f.seek(5, 1) Move file pointer five characters ahead from the current position
File Positions: seek()
f = open( 'second.txt' , 'r')
# read all characters from file
str1 = f.read()
print("Before:",str1)
f.seek(5)
str2 = f.read()
print("After Seek:",str2)
Ex:
import os
os.rename("one.txt","two.txt")
os.remove("three.txt")
Write a Python program to read first n lines of a file.
n=2
f = open( 'crickter.txt' , 'r')
lines=f.readlines()[:n] O/P:
for i in lines: Sachin
Dravid
print(i)
f.close()
Program to count the no of lines ,words and characters in a
file
f = open( 'crickter.txt' , 'r')
contents=f.readlines()
NW=0
NC=0
NL=0
for line in contents:
NL=NL+1
words=line.split()
NW=NW+len(words)
NC=NC+len(line)
O/P:
print("Number of Lines:",NL) Number of Lines: 4
print("Number of Words:",NW) Number of Words: 4
Number of Characters: 28
print("Number of Characters:",NC)
f.close()
Write a python program copy one file content into another file.
f1=open("crickter.txt","r")
f2=open("cri.txt","a")
line=f1.read()
f2.write(line)
Working with CSV files in Python
• CSV (Comma-Separated Values) is one of the file formats for storing and
exchanging tabular data.
import csv
f=open('protagonist.csv', 'r’)
reader = csv.reader(f)
for row in reader: O/P:
print(row) ['SN', 'Movie', 'Protagonist']
['1', 'Lord of the Rings', 'Frodo Baggins']
['2', 'Harry Potter', 'Harry Potter']
Working with CSV files in Python
import csv
f=open('protagonist.csv', 'w’)
writer = csv.writer(f)
writer.writerow(["SN", "Movie", "Protagonist"])
writer.writerow([1, "Lord of the Rings", "Frodo
Baggins"])
writer.writerow([2, "Harry Potter", "Harry Potter"])
Working with CSV files in Python
Creating a Directory
import os
os.mkdir('mydir’)
Change Directory
import os
os.chdir('mydir’)
Renaming a Directory
import os
os.rename('mydir','mydir2’)
Deleting a Directory
import os
os.rmdir('mydir’)