Python Strings
Python Strings
Samir V
Two types of files 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.
A regular text file can be understood as a sequence of characters consisting of
alphabets, numbers and other special symbols. These files are with extensions
like .txt, .py etc
Few text file contents are usually separated comma (,) or tab (\t).Thse files are
called csv (comma separated value) or tsv(tabs seperated value) respectively
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.
Binary files are stored in a computer in a sequence of bytes. Even a single bit
change can corrupt the file and make it unreadable to the supporting
application.
Binary files operations are faster than text file as it is deliminator free hence
translation is not required.
slide 2
Samir V
In Python, there are six methods or access modes, which are:
Read Only ('r’): This mode opens the text files for reading only. It raises the I/O
error if the file does not exist. This is the default mode for opening files as well.
Read and Write ('r+’): This method opens the file for both reading and writing. If
the file does not exist, an I/O error gets raised.
Write Only ('w’): This mode opens the file for writing only. The data in existing files
are overwritten. If the file does not already exist in the folder, a new one gets
created.
Write and Read ('w+’): This mode opens the file for both reading and writing. The
text is overwritten and deleted from an existing file.
Append Only ('a’): This mode allows the file to be opened for writing. If the file
doesn't yet exist, a new one gets created. The newly written data will be added at
the end, following the previously written data.
Append and Read (‘a+’): Using this method, you can read and write in the file. If the
file doesn't already exist, one gets created. The newly written text will be added at
the
slide 3 end.
Samir V
Opening a file
To open a file in Python, we use the open() function. The syntax of open() is
as follows:
file_object= open(file_name, access_mode)
This function returns a file object called file handle which is stored in the
variable file_object. This file handle is used to transfer data to and from the
file (read and write).
If the file does not exist, the above statement creates a new empty file and
assigns it the name we specify in the statement.
The file handle has certain attributes that tells us basic information about
the file, such as: file location, mode, capacity, metadata etc.
slide 4
Samir V
Notice the doble slashes in file path "D:\\Text\\MyFile2.txt“
This is to avoid escape sequences. For eg. \t inserts tab space.
If you do not want to add double slashes, python provide alternate way-
One need to r preceding the file path. This tells interpreter to treat the path
as raw string.
slide 5
Samir V
Closing a file
Here, file_object is the object that was returned while opening the file.
Python makes sure that any unwritten or unsaved data is flushed off
(written) to the file before it is closed. Hence, it is always advised to
close the file once our work is done.
file1 = open("MyFile.txt","a")
….
….
file1.close()
slide 6
Samir V
WRITING TO A TEXT FILE
For writing to a file, we first need to open it in write or append mode. If we open
an existing file in write mode, the previous data will be erased, and the file
object will be positioned at the beginning of the file.
On the other hand, in append mode, new data will be added at the end of the
previous data as the file object is at the end of the file.
After opening the file, we can use the following methods to write data in the file.
• write() - for writing a single string
File_object.write(str1)
myobject=open("myfile.txt",'w’)
marks=58
#number 58 is converted to a string using str()
myobject.write(str(marks))
slide 8
Samir V
• writelines() - for writing a sequence of strings
Syntax - File_object.writelines(L) for L = [str1, str2, str3]
file1.writelines(lst)
file1.close()
print("Data is written into the file.")
slide 9
Samir V
Python includes the following some built-in methods to manipulate strings −
Samir V
3) count():- Python string method count() returns the number of occurrences
of substring sub in the range [start, end].
sub = "wow"
print (str.count(sub))
>> 1
Samir V
4) find():-
Python string method find() determines index, if string str occurs in string, or
in a substring of string if starting index beg and ending index end are given.
Syntax: str.find(str, beg, end) This method return index number if str found
otherwise -1.
e.g.:
str1 = "this is string example....wow!!!”
str2 = "exam"
print str1.find(str2)
print str1.find(str2, 10)
print str1.find(str2, 40)
>> 8 Samir V
5) index():- Python index() determines index, if string str occurs in string, or
in a substring of string if starting index beg and ending index end are given.
This method is same as find(), but raises an exception if sub is not found.
6) islower():- This method checks whether all characters (letters) of the string
are lowercase. If yes it will return TRUE else FALSE
Syntax: str.islower()
Eg -
my_string = "hello"
str1 = '-'
result = str1.join(my_string)
print(result)
>> h-e-l-l-o
result = str2.join(list_1)
print(result)
e.g.:
str = "this is string example....wow!!!"
print "Length of the string: ", len(str)
O/P: Length of the string: 32
10) lower():- Python string method lower() returns a copy of the string in
which all case-based characters have been lowercased.
Syntax: str.lower()
11) upper():- Python string method upper() returns a copy of the string in
which all case-based characters have been uppercased.
Syntax: str.upper()