0% found this document useful (0 votes)
13 views51 pages

Strings, Files and Type Conversions

The document provides an overview of various Python programming concepts, including numeric types (int, float, complex), type conversion, mathematical functions, random number generation, string manipulation, and file handling. It covers the creation and manipulation of strings, operations on strings, and methods for file I/O. Additionally, it includes examples and explanations for each topic to aid understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views51 pages

Strings, Files and Type Conversions

The document provides an overview of various Python programming concepts, including numeric types (int, float, complex), type conversion, mathematical functions, random number generation, string manipulation, and file handling. It covers the creation and manipulation of strings, operations on strings, and methods for file I/O. Additionally, it includes examples and explanations for each topic to aid understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

• Introduction to Different Numeric Types,

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))

T Seshu Chakravarthy Department Of Computer Science and Engineering


Introduction to Different Numeric Types
Complex
• Complex numbers are written with a "j" as the imaginary part:

x = 3+5j
y = 5j
z = -5j

print(type(x))
print(type(y))
print(type(z))

T Seshu Chakravarthy Department Of Computer Science and Engineering


Type Conversion
• You can convert from one type to another with the int(), float(), and complex() methods:
#convert from int to float:
x = float(1)

#convert from float to int:


y = int(2.8)

#convert from int to complex:


z = complex(1)

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'>

T Seshu Chakravarthy Department Of Computer Science and Engineering


25

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

# Return the remainder of x/y


print(math.fmod(20, 4)) 0
print(math.fmod(20, 3)) 2

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

#Return factorial of a number


print(math.factorial(3)) #6
print(math.factorial(5))
#120

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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Random Numbers
randint():Returns a random number between the given range

import random
#returns a number between 3 and 9 (both included)
print(random.randint(3, 9)) #4

random(): Returns a random float number between 0 and 1

import random

print(random.random()) #0.627

choice() : The choice() method returns a randomly selected element from the specified
sequence.

import random

mylist = ["apple", "banana", "cherry"] apple


print(random.choice(mylist))

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python program where the user has to guess a randomly
generated number
import random

def guess_the_number():
# Generate a random number between 1 and 100
secret_number = random.randint(1, 100)

print("Welcome to Guess the Number Game!")


attempts = 0

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()

T Seshu Chakravarthy Department Of Computer Science and Engineering


Strings
• String is sequence/array of characters.
• Strings in python are surrounded by either single quotation marks, or double
quotation marks.

• a=‘hello’ b=“Python”

T Seshu Chakravarthy Department Of Computer Science and Engineering


Indexing, and Slicing
str = 'programiz'
print( str[0])
print(str[-1])
p
print(str[:3] ) z
print(str[4:] ) pro
ramiz
print(str[1:5] ) rogr
print(str[5:-2]) am
programizprogramizprogramiz
print( str * 3)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Operations on Strings
Compare Two Strings
• We use the == operator to compare two strings. If two strings are
equal, the operator returns True. Otherwise, it returns False.

Example:
str1 = "Hello, world!"
str2 = "I love Python."
str3 = "Hello, world!"

# compare str1 and str2


print(str1 == str2) False
True
# compare str1 and str3
print(str1 == str3)
T Seshu Chakravarthy Department Of Computer Science and Engineering
Operations on Strings
Join Two or More Strings
• In Python, we can join (concatenate) two or more strings
using the + operator.

greet = "Hello, "


name = "Jack"
result = greet + name
print(result)

# Output: Hello, Jack

T Seshu Chakravarthy Department Of Computer Science and Engineering


Operations on Strings
Python String Length
• In Python, we use the len() method to find the length of a string.

greet = 'Hello’
print(len(greet)) # Output: 5

String Membership Test


• We can test if a substring exists within a string or not, using the keyword in

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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Looping Through a String Programs
1. Write a python program to count no of a’s in your name?
Ex: Devansh o/p: 1

2. Write a python program to remove the vowels in the given string

3 . Write a pthon program Remove Punctuations From a String


I/P: "Hello!!!, he said ---and went.“
O/P: Hello he said and went

T Seshu Chakravarthy Department Of Computer Science and Engineering


Write a python program to count no of a’s in your name?

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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Program to remove the vowels in the given string
vowels="aeiou"
my_str = "Hello I am Devansh"
no_vowel = ""
for char in my_str:
if char not in vowels:
no_vowel= no_vowel + char
print(no_vowel)

Hll I m Dvnsh

T Seshu Chakravarthy Department Of Computer Science and Engineering


Program Remove Punctuations From a String

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

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods

count():The count() method returns the number of times a specified value appears in the
string.

txt = "I love apples, apple is my favorite fruit"


x = txt.count("apple")
print(x) O/P: 2

capitalize() :It converts the first character of a string to upper case and the rest is lower
case.

txt = "python is FUN!"


x = txt.capitalize()
print (x) O/P: Python is fun!

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods

• The startswith() method returns True if the string starts with the specified value,
otherwise False.

txt = "welcome to my world."


x = txt.startswith("wel")
print(x) O/P: True

• The endswith() method returns True if the string ends with the specified value,
otherwise False.

txt = "Hello, welcome to my world."


x = txt.endswith("world.")
print(x)
O/P: True

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods
find():Searches the string for a specified value and returns the position of first occurrence where
it was found
• The find() method returns -1 if the value is not found.
rfind(): Searches the string for a specified value and returns the position of last occurrence
where it was found
1
txt = "Hello, welcome to my world."
13
x = txt.find("e")
y = txt.rfind("e")
print(x)
print(y)

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)

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods

split():Splits the string based on separator, and returns a list

Ex1:
txt = "welcome to the Python Class"
x = txt.split()
print(x) O/P: ['welcome', 'to', 'the', 'Python', ‘Class']

Ex2:

txt = "hello, my name is Peter, I am 26 years old"


x = txt.split(", ")
print(x) ['hello', 'my name is Peter', 'I am 26 years old']

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods

• 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

txt = " banana "


x = txt.strip()
y = txt.lstrip()
z = txt.rstrip()
print(x)
print(y)
banana
print(z) banana
banana

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods
• The replace() method replaces a specified value with another value. .
txt = "one one was a race horse"
x = txt.replace("one", "three")
print(x)
O/P: three three was a race horse
• upper() : Converts a string into upper case

txt = "Hello my friends"


x = txt.upper()
print(x) O/P: HELLO MY FRIENDS

lower() :Converts a string into lower case

txt = "Hello my FRIENDS"


x = txt.lower()
print(x) O/P: hello my friends

T Seshu Chakravarthy Department Of Computer Science and Engineering


Python String Methods
• The join() method takes all items from list/tuple and joins them into one string.

mylist = ["John", "Peter", "Vicky"]


x = " ".join(mylist)
print(x)
O/P: John Peter Vicky

T Seshu Chakravarthy Department Of Computer Science and Engineering


Program to sort alphabetically the words form a
string
Version-1:
a
my_str = "hi this is a python class" class
words= my_str.split() hi
words.sort() is
python
this
for i in words:
print(i)

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.

Syntax: f= open(filename, mode)

• 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

close(): Closes an opened file.


f = open("demofile.txt", "r")
f.close()
Write Operations: write()
• The write() function writes any string to an open 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

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()

Ex: Open the file “first.txt" and append the content

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()

Read only Parts of the File:

f = open( 'first.txt' , 'r')


str1 = f.read(5)
print(str1) O/P: Hello
f.close()
Read Operations: readline()
• Using the readline() method, we can read a file line by line.
• by default, this method reads the first line in the file.
• For example, If you want to read the first five lines from a text file, run a loop five
times, and use the readline() method in the loop’s body.
• Using this approach, we can read a specific number of lines.

Reading First N lines From a File Using readline():

f = open( ‘crickter.txt' , 'r')

for i in range(3): O/P:


print(f.readline()) Sachin
f.close() Dravid
Ganguly
Read Operations: readlines()
• readlines() method read entire file contents line by line into a list.

f = open( 'crickter.txt' , 'r') O/P:


print(f.readlines()) ['Sachin\n', 'Dravid\n', 'Ganguly\n', 'Laxman']
f.close()

Reading last N lines from a file

N=2
f = open( 'crickter.txt' , 'r') O/P:
print(f.readlines()[N:]) ['Ganguly\n', 'Laxman']
f.close()

Reading File in Reverse Order

f = open( 'crickter.txt' , 'r')


O/P:
lines = f.readlines()
Laxman
rev_lines=reversed(lines)
Ganguly
for i in rev_lines:
Dravid
print(i)
Sachin
File Positions: seek()
• The seek() function sets/change the position of a file pointer.
Syntax:
f.seek(offset, whence)
• How many points the pointer will move is computed from adding offset to a
reference point; the reference point is given by the whence argument

•A whence value of 0 means from the beginning of the file.


•A whence value of 1 uses the current file position
•A whence value of 2 uses the end of the file as the reference point.

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)

Before: Hello this is VVIT-AP


f.seek(0,2) After Seek: this is VVIT-AP
AFter End:
str3 = f.read()
print("AFter End:",str3)
f.close()
Renaming and Deleting Files
• rename() method is used to rename a file
• remove() function is used to delete a file
• These methods are a part of the os module

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.

Reading CSV files Using csv.reader()


• To read a CSV file in Python, we can use the csv.reader() function.

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

Writing CSV files Using csv.writer():


• To write to a CSV file in Python, we can use the csv.writer() function.
• The csv.writer() function returns a writer object that converts the user's data into
a delimited string.
• This string can later be used to write into CSV files using the writerow() function.

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

Writing multiple rows with writerows():

import csvf=open('protagonist.csv', 'w’)


writer = csv.writer(f)
csv_rowlist = [["SN", "Movie", "Protagonist"], [1, "Lord of the
Rings", "Frodo Baggins"],[2, "Harry Potter", "Harry Potter"]]
writer.writerows(csv_rowlist)
various directory handling functions

Creating a Directory
import os
os.mkdir('mydir’)

Get Current Working Directory


Current working directory: C:\Users\chvrr
import os
cwd = os.getcwd()
print("Current working directory:", cwd)

Listing Files and Directories


import os
print(os.listdir('.'))
various directory handling functions

Change Directory
import os
os.chdir('mydir’)

Renaming a Directory
import os
os.rename('mydir','mydir2’)

Deleting a Directory
import os
os.rmdir('mydir’)

You might also like