0% found this document useful (0 votes)
9 views13 pages

Unit 5

ch5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

Unit 5

ch5
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Scripting Language – Python (4330701)

Unit 5 String Processing and File Handling


5.1 Introduction to String
 A string is a sequence of characters.
 Strings can be created by enclosing characters inside a single quote or double-quotes.
 A string that contains no characters are called empty string.
Example:

s='Hello' Output:
print(s)
Hello
s= "Hello" Hello
print(s) Hello
Hello, welcome to
s = '''Hello''' the world of Python
print(s)

s = """Hello, welcome to
the world of Python"""
print(s)

String Operation
Create list of strings
 To create a list of strings, first use square brackets [ ] to create a list.
 Then place the list items inside the brackets separated by commas.
 strings must be surrounded by quotes.
 use = to store the list in a variable.
Ex:
colors = ["red", "blue", "green"]
Ex:
colors = [
"red",
"blue",
"green"
]
Print list of strings
 To print a whole list of strings in one line, you can simply call the built-in print function,
colors = ["red", "blue", "green"] Output
print(colors) ['red', 'blue', 'green']

Add strings to list


 When you already have a list of strings and you want to add another string to it, you can use
the append method:
colors = ["red", "blue", "green"]
colors.append("black")
print(colors)
 You can also create a new list with only one string in it and add it to the current list:
colors = ["red", "blue", "green"] Output:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 1


Scripting Language – Python (4330701)
colors=colors+["black"] ['red', 'blue', 'green', 'black']
print(colors)

Print list as string

 If you want to convert a list to a string, you can use the built-in function repr to make a string
representation of the list:

colors = ["red", "blue", "green"] Output:

print(type(colors)) <class 'list'>

colors_str=repr(colors) <class 'str'>

print(type(colors_str))
Concatenate lists of strings

 You can use the + operator to concatenate two lists of strings. For example:

color1 = ["red", "blue"] Output:

color2 = ["black", "whilte"] ['red', 'blue', 'black', 'whilte']

color= color1 + color2

print(color)
Check if string is in list

 You can use the in keyword to check if a list contains a string.


 This gives you a boolean value: either True or False.
 You can store this value somewhere, or use it directly in an if statement:

colors = ["red", "blue"] Output:

if "blue" in colors: yes!

print("yes!") True

ans = "blue" in colors

print(ans)

Sort list of strings

 To sort a list of strings, you can use the sort method:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 2


Scripting Language – Python (4330701)
colors = ["red", "white","blue"] Output:
colors.sort() ['blue', 'red', 'white']
print(colors)

 You can also use the sorted() built-in function:


colors = ["red", "white","blue"] Output:
colors=sorted(colors)
print(colors) ['blue', 'red', 'white']

Join list of strings

 To join a list of strings by another string, you need to call the join method on the string, giving your
list as an argument. For example, if we have this list:
colors = ["red", "white","blue"] Output:
print("".join(colors)) redwhiteblue
print(" ".join(colors)) red white blue
print("|".join(colors)) red|white|blue
5.2 Access String elements using index operator

 You can use a for loop,range in python and slicing operator to traverse a character in a string.
Using for loop to traverse a string
str="python" Output:
for s in str: p
print(s) y
t
h
o
n
Using range to traverse a string:
str="python" Output:
for s in range(len(str)): p
print(str[s]) y
t
h
o
n
Using slicing operator to traverse a string partially
 A segment of a string is called a slice.
 Selecting a slice is similar to selecting a character:
 Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0 in the
beginning of the string and working their way from -1 at the end.
 Slice out substrings, sub lists, sub Tuples using index.

Syntax:[Start: stop: steps]


 Slicing will start from index and will go up to stop in step of steps.
 Default value of start is 0,
 Stop is last index of list
 And for step default is 1

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 3


Scripting Language – Python (4330701)
str = 'Hello World!' Output
print (str ) Hello World!
print(str[0] ) H
print (str[2:4]) ll
print (str[2:] ) llo World!
print (str * 2) Hello World!Hello World!
str="Scripting Language python" Output
for s in str[0:6:1]: Script
print(s)

str="Scripting Language python" Output


for s in str[::3]: Sii na tn
print(s)
str="python" Output
for s in str[::-1]: nohtyp
print(s)
str="Python" Output
print(str[::-1]) nohtyp
Using indexing ,print backward string

str="Python" Output
l=len(str)-1 n
while l>=0: o
print(str[l]) h
l=l-1 t
y
p

5.3 String functions


● Basic functions: len, max, min
len( ): It returns number of characters in the string
syntax: variable name=len(string)
Example:
s=”python”
l=len(s)
print(l)
Output:6
min( ): It finds the smallest element in the sequence.
For one string, the character that has the smallest code is selected in the string.
For multiple string, a string is selected which,in lexicographic order (dictionary order) ,follows
the first alphabetically.
Syntax:
ans=min(s)
Or
ans=min(s1,s2,…sn)
s="python" Output:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 4


Scripting Language – Python (4330701)
print(min(s)) h
s='abc+-0' +
print(min(s)) 0
s='012345' A
print(min(s))
s='aAbB'
print(min(s))
s=("def","abc","xyz") Output:
print(min(s)) abc
s=('+','-','*','/') *
print(min(s))
max( ): It finds the largest element in the sequence.
For one string, the character that has the largest code is selected in the string.
For multiple string, a string is selected which, in lexicographic order, follows the last
alphabetically.
Syntax:
ans=max(s)
Or
ans=max(s1,s2,…sn)
s="python" Output:
print(max(s))
s='abc+-0' y
print(max(s)) c
s='012345' 5
print(max(s)) b
s='aAbB'
print(max(s))
s=("def","abc","xyz") Output:
print(max(s)) xyz
s=('+','-','*','/') /
print(max(s))

● Testing functions: isalnum, isalpha, isdigit, isidentifier, islower, isupper, and isspace
isalnum(): returns True if all the characters in the string is alphanumeric (a string which contains
either number or alphabets or both). Otherwise return False
s=" " Output:
print(s.isalnum()) False
s="abc" True
print(s.isalnum()) True
s='123' True
print(s.isalnum()) False
s='abc123' False
print(s.isalnum())
s='+-'
print(s.isalnum())
s='a b'
print(s.isalnum())

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 5


Scripting Language – Python (4330701)
isalpha: returns True if all the characters in the string are alphabets. Otherwise return False
s=" " Output:
print(s.isalpha()) False
s="abc" True
print(s.isalpha()) False
s='123' False
print(s.isalpha()) False
s='abc123'
print(s.isalpha())
s='+-'
print(s.isalpha())
Isdigit: returns True if all the characters in the string are digits. Otherwise return False.
Output:
print("abc123".isdigit()) False
print("123".isdigit()) True
print("101 ".isdigit()) False
print("101.129".isdigit()) False
Isidentifier: returns True if string is an identifier or a keyword that is valid according to the python
syntax Otherwise return False.
print("hello".isidentifier()) Output:
print("a1".isidentifier()) True
print("1a".isidentifier()) True
print("for".isidentifier()) False
True
islower: returns True if all the characters in the string are in lowercase. Otherwise return False.
s = 'Python' Output:
print(s.islower()) False
print("abc".islower()) True

isupper: returns True if all the characters in the string are in uppercase. Otherwise return False.
s = 'PYthon' Output:
print(s.isupper()) False
print("ABC".isupper()) True

isspace : returns True if all the characters in the string are whitespace characters. Otherwise return
False.
print("\n\t".isspace()) Output:
print(" \n\t".isspace()) True
print("@ \n\t".isspace()) True
print("123".isspace()) False
False

● Searching functions: endswith, startswith, find, rfind, count


endswith: Syntax: endswith(suffix, start, end)
 Returns True when a string ends with the characters specified by suffix.
 You can limit the check by specifying a starting index using start or an ending index using end.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 6


Scripting Language – Python (4330701)
 If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and
ending indexes
s="abcdef" Output:
print(s.endswith('ef')) True
print("abcdef".endswith('ef',2,6)) True
print("abcdef".endswith('ef',2,4)) False
s1=('ab','cd','ef')
s2="abcd 123 ef" True
print(s2.endswith(s1,0,len(s2)))

startswith: Syntax:startswith(prefix, start, end):


 Returns True when a string begins with the characters specified by prefix.
 You can limit the check by specifying a starting index using start or an ending index using end.
 If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and
ending indexes.
s="Hello" Output:
print(s.startswith('He')) True
print(s.startswith('lo')) False
print(s.startswith('He',0)) True
print(s.startswith('He',0,len(s))) True
print(s.startswith('He',2)) False
print("12345".startswith('123',0,4)) True
print("12345".startswith('123',2,4)) False

Find: Syntax: find(str, start, end):


 Check whether str occurs in a string and outputs the index of the location.
 You can limit the search by specifying starting index using start or a ending index using end.
 If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and
ending indexes .
 If search not found then it returns -1.
s = 'Hello World' Output:
ans = s.find('Hello') Substring found at index: 0
print("Substring found at index:", ans) 6
2
print(s.find('Wo')) -1
print(s.find('l', 2)) 4
print(s.find('a', 2))
print(s.find('o', 2, 10))
rfind: Syntax: rfind(str, start, end):
 Provides the same functionality as find(), but searches backward from the end of the string instead
of the starting.
 You can limit the search by specifying starting index using start or a ending index using end.
 If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and
ending indexes .
 If search not found then it returns -1.
s = 'Hello World' Output:
ans = s.rfind('Hello')

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 7


Scripting Language – Python (4330701)
print("Substring found at index:", ans) Substring found at index: 0
6
print(s.rfind('Wo')) 9
print(s.rfind('l', 2)) -1
print(s.rfind('a', 2)) 7
print(s.rfind('o', 2, 10))

count: Syntax: count(str, start, end):


 Counts how many times str occurs in a string.
 You can limit the search by specifying a starting index using start or an ending index using end.
 If start and end indexes are not provided then, by default it takes 0 and length-1 as starting and
ending indexes.

s= "Hello Students Hello" Output:


print(s.count("Hello", 0, 5)) 1
print(s.count("Hello", 0, 20)) 2
print(s.count('l',0,20)) 4
print(s.count('c',0,20)) 0

● Manipulation functions:
capitalize( ): It returns a copy of the original string and converts the first character of the string to a
capital (uppercase) letter, while making all other characters in the string lowercase letters.
Syntax: string_name.capitalize()
s= "hello world" Output:
print(s.capitalize()) Hello world
print("heLLo".capitalize()) Hello
print('123'.capitalize()) 123
lower( ): This function converts all uppercase characters in a string into lowercase characters and
returns it.
Syntax: string.lower()
s= "HEllo" Output:
print("Original string:",s) Original string: HEllo
print("Converted string:"+s.lower()) Converted string:hello
upper ( ): This function converts all lowercase characters in a string into uppercase characters and
returns it.
Syntax: string.upper()
s= "HEllo" Output:
print("Original string:",s) Original string: HEllo
print("Converted string:"+s.upper()) Converted string:HELLO
title ( ): It converts the first character in each word to uppercase and the remaining characters to
lowercase in the string and returns a new string.
Syntax: string.title()
s= "hELLo good morning" Output:
print("Original string:",s) Original string: hELLo good morning
print("Converted string:"+s.title()) Converted string:Hello Good Morning
swapcase: The string swapcase() method converts all uppercase characters to lowercase and lowercase
characters to uppercase of the given string, and returns it.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 8


Scripting Language – Python (4330701)
Syntax: string.swapcase()
s= "hELLo GOOD morning" Output:
print("Original string:",s) Original string: hELLo GOOD morning
print("Converted string:"+s.swapcase()) Converted string: HellO good MORNING
replace: It returns a copy of the string where all occurrences of a substring are replaced with another
substring.
Syntax: string.replace(old_string, new_string, count)
s="Hello World" Output:
s1=s.replace("l", "L") Hello World
s2=s.replace("o","O",1) HeLLo WorLd
print(s) HellO World
print(s1)
print(s2)
lstrip: It returns a copy of the string with leading characters removed (based on the string argument
passed). If no argument is passed, it removes leading spaces.
Syntax: string.lstrip([characters])

Here,characters [optional]: A set of characters to remove as leading characters. By default, it uses


space as the character to remove.
s=" Hello" Output:
print(s.lstrip()) Hello
s="++..--$Hello" $Hello
print(s.lstrip("+.-"))
rstrip: It returns a copy of the string with trailing characters removed (based on the string argument
passed). If no argument is passed, it removes trailing spaces.

Syntax: string.rstrip([characters])
Parameters: characters (optional) – a string specifying the set of characters to be removed.
s="Hello " Output:
print(s.rstrip()) Hello
s="Hello+..+&.." Hello
print(s.rstrip('.+&'))
strip: It is an inbuilt function in the Python programming language that returns a copy of the string
with both leading and trailing characters removed.
Syntax: string.strip([characters])
s=" Hello World..." Output:
print(s) Hello World...
print(s.strip()) Hello World...
print(s.strip('.')) Hello World
casefold: Python String casefold() method is used to convert string to lower case. It is similar to
lower() string method, but case removes all the case distinctions present in a string.
 For example, the German letter ß is already lowercase so, the lower() method doesn't make the
conversion.
 But the casefold() method will convert ß to its equivalent character ss.

Syntax: string.casefold()
s="HELLO" Output:

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 9


Scripting Language – Python (4330701)
print(s.casefold()) hello
print(s.lower()) hello

● Formatting functions:
format: The format() method formats the specified value(s) and insert them inside the string's
placeholder. The placeholder is defined using curly brackets: {}. It is used for handling complex string
formatting more efficiently.
Syntax: string.format(value1, value2...)
a=5 Output:
b=10 5+10=15
s='{0}+{1}={2}'.format(a,b,a+b)
print(s)
a=5 Output:
s='{0}**{1}={2}'.format(a,2,a**2) 5**2=25
print(s)
s="My name is {fname}".format(fname = "abc") Output:
print(s) My name is abc
center: It creates and returns a new string that is padded with the specified character.
Syntax: string.center(length[, fillchar])
length: length of the string after padding with the characters.
fillchar: (optional) characters which need to be padded. If it’s not provided, space is taken as
the default argument.
s="Hello World" Output:
print(s.center(20)) Hello World
print(s.center(5)) Hello World
print(s.center(20,"#")) ####Hello World#####
print(s.center(5,"#")) Hello World

ljust: This method left aligns the string according to the width specified and fills the remaining space
of the line with blank space if ‘fillchr‘ argument is not passed.

Syntax: ljust(len, fillchr)


len: The width of string to expand it.
fillchr (optional): The character to fill in the remaining space.
s = "hello" Output:
print(s.ljust(10)) hello
print(s.ljust(10, '-')) hello-----
print(s.ljust(10, '#')) hello#####

rjust: This method left aligns the string according to the width specified and fills the remaining space
of the line with blank space if ‘fillchr‘ argument is not passed.
Syntax: rjust(len, fillchr)
len: The width of string to expand it.
fillchr (optional): The character to fill in the remaining space.

s = "hello" Output:
print(s.rjust(10)) hello

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 10


Scripting Language – Python (4330701)
print(s.rjust(10, '-')) -----hello
print(s.rjust(10, '#')) #####hello
5.4 Introduction to Text files
 Python provides inbuilt functions for creating, writing, and reading files.
 There are two types of files that can be handled in python, normal text files and binary files (written
in binary language, 0s, and 1s).

 Text files: In this type of file, Each line of text is terminated with a special character called EOL
(End of Line), which is the new line character (‘\n’) in python by default.

 Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.

 Difference between Text files and Binary files:


Text files Binary files
Data stores in ASCII or Unicode . Contains raw data
Content written in text files is human readable. Content written in binary files is not human
readable
Slower than binary file. Faster than text file.
Text files are used to store data more user Binary files are used to store data more
friendly. compactly.

Files
 Files are named locations on disk to store related information.
 They are used to permanently store data in a non-volatile memory (e.g. hard disk).
 When we want to read from or write to a file, we need to open it first.
 When we are done, it needs to be closed so that the resources that are tied with the file are freed.
 In Python, a file operation takes place in the following order:
 Open a file
 Read or write (perform operation)
 Close the file

5.5 File Handling functions:


● Basic functions: open, close
open File:
 Before performing any operation on the file like reading or writing, first, we have to open that file.
 For this, we should use Python’s inbuilt function open()
 At the time of opening, we have to specify the mode, which represents the purpose of the opening
file.
Syntax: file object = open(filename, access mode)
Example: f = open("a.txt", "r")

Where the following mode is supported:


r open an existing file for a read operation.
w open an existing file for a write operation. If the file already contains some data then it will be
overridden but if the file is not present then it creates the file as well.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 11


Scripting Language – Python (4330701)
a open an existing file for append operation. It will not override existing data.
r+ To read and write data into the file. The previous data in the file will be overridden
w+ To write and read data. It will override existing data.
a+ To append and read data from the file. It will not override existing data.
close File:
 close() function closes the file and frees the memory space acquired by that file.
 It is used at the time when the file is no longer needed or if it is to be opened in a different file
mode.
Syntax: File object.close()
Example: f = open("a.txt", "r")
f.close()
● Reading file:
 To read a file in Python, we must open the file in reading (r) mode.
 There are three ways to read data from a text file.
read, readline and readlines.

read( ) : Returns the read bytes in form of a string. It reads n bytes, if no n specified, reads the entire
file.
Syntax: File object.read([n])
f=open("a.txt","r") Output:
print(f.read( )) hello everyone
f.close() Good morning
f=open("a.txt","r") Output:
print(f.read(14)) hello everyone
f.close()

readline( ) : Reads a line of the file and returns in form of a string. For specified n, reads at most n
bytes. It does not reads more than one line.
Syntax: File object.readline([n])
f=open("a.txt","r") Output:
print(f.read(5)) hello
f.close()
f=open("a.txt","r") Output:
print(f.readline()) hello everyone
f.close()

Readlines( ): Reads all the lines and return them as each line a string element in a list.
Syntax: File_object.readlines()
f=open("a.txt","r") Output:
print(f.readlines( )) ['hello everyone\n', 'Good morning\n', 'Have a nice day\n']
f.close()

● writing file: write, append, writelines


 To write a file in Python, we must open the file in writing (w) mode or append mode(a).
write():The write() method writes a string to a text file.
Syntax: File_object.write(str1)
Inserts the string str1 in a single line in the text file.

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 12


Scripting Language – Python (4330701)
f=open("E:/a.txt","w") Output:
f.write("Hello World") Open a.txt file ….. Hello World is display in text
f.close() file.
append: To append to a text file, you need to open the text file for appending mode.
When the file is opened in append mode, the handle is positioned at the end of the file. The data being
written will be inserted at the end, after the existing data.
f=open("E:/a.txt","a") Output:
f.write("Good Morning") Open a.txt file ….. Hello World Good Morning
f.close() is display in text file.

writelines():The writelines() method write a list of strings to a file at once.


Syntax: File_object.writelines(L) for L = [str1, str2, str3]
For a list of string elements, each string is inserted in the text file. Used to insert multiple
strings at a single time.
f=open("E:/a.txt","w") Output:
lines=["Hello\n","good\n","morning"] Open a.txt file …..Below content is displayed in
f.writelines(lines) text file.
f.close()
Hello
good
morning

Prepared by: Mrs. Ami J. Patel (Lecturer in CE Dept.) Page 13

You might also like