0% found this document useful (0 votes)
16 views19 pages

Python Notes Part2 Strings File Handling - No

Unit II covers string manipulations in Python, including indexing, slicing, and common string methods, as well as file handling techniques for reading and writing text files. It explains the creation and manipulation of strings, their immutability, and various methods for file operations such as reading, writing, and appending data. Additionally, the document discusses string formatting and conversion between number systems.

Uploaded by

cutandkeystudios
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)
16 views19 pages

Python Notes Part2 Strings File Handling - No

Unit II covers string manipulations in Python, including indexing, slicing, and common string methods, as well as file handling techniques for reading and writing text files. It explains the creation and manipulation of strings, their immutability, and various methods for file operations such as reading, writing, and appending data. Additionally, the document discusses string formatting and conversion between number systems.

Uploaded by

cutandkeystudios
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

Unit II

String Manipulations: String indexing and slicing, Subscript operator, String methods and
operations, String conversion with number systems

Text File Handling: Reading and writing text files, Writing/Reading numbers as strings, File
modes

Formatted Files: Working with CSV and tab-separated files using csv module, Reading from and
writing to CSV, Tab-separated file handling

In Python, a string is a sequence of characters enclosed in quotes. It can include letters, numbers,
symbols or spaces. Since Python has no separate character type, even a single character is treated
as a string with length one. Strings are widely used for text handling and manipulation.

Creating a String

Strings can be created using either single ('...') or double ("...") quotes. Both behave the same.

Example: Creating two equivalent strings one with single and other with double quotes.

s1 = 'WELCOME' # single quote

s2 = "WELCOME" # double quote

print(s1)

print(s2)

Multi-line Strings

Use triple quotes ('''...''' ) or ( """...""") for strings that span multiple lines. Newlines are
preserved.

Example: text = """This is a multi-line string.

It can span multiple lines.

Each line break is preserved."""

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 1
print(text)

Accessing characters in String

n Python, a string is an indexed sequence, which means each character has a position (index)
and can be accessed individually.

• Positive indexing starts from 0 (left to right)

• Negative indexing starts from -1 (right to left)

Example:

text = "PYTHON"

Index positions

P Y T H O N

0 1 2 3 4 5 ← Positive indexing

-6 -5 -4 -3 -2 -1 ← Negative indexing

Example 1: Access Characters Using Positive Indexing

text = "PYTHON"
print(text[0]) # First character
print(text[2]) # Third character
print(text[5]) # Last character

output: P T N

Example 2: Access Characters Using Negative Indexing

text = "PYTHON"
print(text[-1]) # Last character
print(text[-2]) # Second last character
print(text[-6]) # First character
OUTPUT: N O P

String Slicing

String slicing allows to extract a portion (substring) of a string using a special syntax. It is
very powerful and commonly used when working with text.

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 2
Syntax: string[start : stop : step]

Part Meaning

start - Index to begin slicing (inclusive)

stop - Index to end slicing (exclusive)

step - Gap between characters (optional)

Predict the Output

s = "Information"

print(s[0:4]) info

print(s[3:8]) ormat

print(s[:5]) infor

print(s[5:]) mation

print(s[-4:]) tion

print(s[::2]) #from the beginning every second character ifrain

print(s[::-1]) # reverse the string noitamrofni

print(s[::-2]) niarfi

OUTPUT
Info

Ormat

Infor

Mation

Tion

Ifrain

noitamrofnI

What is the difference between text[:] and text[::-1]?


PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 3
Copy of the String

Reverse the String

Example;

text = "Python"

print(text[:])

text = "Python"

print(text[::-1])

String Iteration

Strings are iterable; they can be loop through characters one by one.

Example: it print each character in one line.

s = "Python"
for char in s:
print(char)

example1: using for loop


text = "Python"
for i in range(len(text)):
print(text[i])

String Immutability

Strings are immutable, which means that they cannot be changed after they are created. String
manipulations is done using methods like concatenation, slicing or formatting to create new
strings based on original.

NOTE: Strings are immutable, but variable names can be reassigned to new string objects.

Example:

text = "Python"

text[0] = "J" # Trying to change 'P' to 'J'

output: error

Example: In this example we are changing first character by building a new string.
PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 4
s = "bca"

s = "m" + s[1:] # create new string

print(s)

Deleting a String

it is not possible to delete individual characters from a string since strings are immutable. But we
can delete an entire string variable using the del keyword.

Example: we are using del keyword to delete a string.

s = "presidency"

del s

Note: After deleting the string if we try to access s then it will result in a NameError because
variable no longer exists.

Updating a String

As strings are immutable, “updates” create new strings using slicing or methods such
as replace().

Example: This code fix the first letter and replace a word.

s = "hello STUDENTS"

s1 = "H" + s[1:] # update first character

s2 = [Link](s, "ENGINEERS") # replace word

print(s1)

print(s2)

Common String Methods – len() , upper(), lower(), strip(), replace()

Python provides various built-in methods to manipulate strings. Below are some of the most
useful methods:

1. len(): The len() function returns the total number of characters in a string (including spaces
and punctuation).

Example:

s = "MCA course#$%"

print(len(s))

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 5
2. upper() and lower(): upper() method converts all characters to uppercase
whereas, lower() method converts all characters to lowercase.

s = "Hello World"

print([Link]())

print([Link]())

3. strip() and replace(): strip() removes leading and trailing whitespace from the string and
replace() replaces all occurrences of a specified substring with another.

Example:
s = " Gfg "
print(s)
print([Link]())

OUTPUT
Gfg
Gfg
s = "Python is fun"
print([Link]("fun", "awesome"))

OUTPUT
Python is awesome

Concatenating and Repeating Strings

We can concatenate strings using + operator and repeat them using * operator.

1. Strings can be combined by using + operator.

Example: Join two words with a space.

s1 = "Hello"

s2 = "World"

print(s1 + " " + s2)

Output

Hello World

2. We can repeat a string multiple times using * operator.

Try Example: Repeat a greeting three times.

s = "Hello "

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 6
print(s * 3)

output

Hello Hello Hello

Formatting Strings

Python provides several ways to include variables inside strings.

1. Using f-strings

The simplest and most preferred way to format strings is by using f-strings.

Example: Embed variables directly using {} placeholders.


name = "Alice"
age = 22
print(f"Name: {name}, Age: {age}")
Output

Name: Alice, Age: 22

2. Using format()

Another way to format strings is by using format() method.

Example: Use placeholders {} and pass values positionally.


name = "Alice"
age = 22
s = "My name is {} and I am {} years old.".format(name, age)
print(s)

Output
My name is Alice and I am 22 years old.

The subscript operator

In Python is the square bracket [] syntax, which is used to access individual elements or a
range of elements (slicing) within sequence data types like strings, lists, and tuples, as well as to
access values in dictionaries by their keys.

Examples

The [] operator is versatile(multi purpose) and works across several built-in data structures.

Accessing Elements by Index (Lists, Tuples, Strings)

Python uses zero-based indexing, meaning the first element is at index 0. Negative indices can be
used to access elements from the end of the sequence (e.g., -1 for the last element).
PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 7
EXAMPLE

# Lists
my_list = [10, 20, 30, 40, 50]
first_element = my_list[0] # Output: 10
last_element = my_list[-1] # Output: 50

# Strings
my_string = "Hello"
first_char = my_string[0] # Output: 'H'

# Tuples
my_tuple = (‘h’,’e’,llo 1, 2, 3, 4, 5)
my_tuple[0]=’w’

second_element = my_tuple[1] # Output: 2

Slicing Elements (Lists, Tuples, Strings)


The subscript operator also supports slicing, which allows us to extract a sub-sequence using the
syntax [start:stop:step].

EXAMPLE
text = "Python Slicing"

# Get a substring from index 0 up to (but not including) index 6

part1 = text[0:6]

# Output: 'Python'

# Get a slice from index 7 to the end

part2 = text[7:]

# Output: 'Slicing'

# Get every second character (using a step)

every_second = text[::2]

# Output: 'Pto licn'

# Reverse the string

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 8
reversed_text = text[::-1]

# Output: 'gnicilS nohtyP'

String conversion with number systems


In Python, we can convert between numbers and their string representations in different number
systems (bases) using built-in functions like int(), str(), bin(), oct(), and hex().

Converting Numbers to Strings (with different bases)


Python provides specific functions to convert an integer to its string representation in binary,
octal, and hexadecimal systems.
• bin(decimal_int): Converts a decimal integer to a binary string with a '0b' prefix.
• oct(decimal_int): Converts a decimal integer to an octal string with a '0o' prefix.
• hex(decimal_int): Converts a decimal integer to a hexadecimal string with a '0x' prefix.
Examples:

OUTPUT??

SAME PROGRAM WITHOUT PREFIX

Output
PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 9
CONVERTING STRINGS TO NUMBERS (FROM DIFFERENT BASES)
The built-in int() function is used to convert strings to integers.

•int(string, base): Converts a string s into a base-10 integer, interpreting the string as a
number in the specified base.
• The base must be an integer between 2 and 36, or 0 (which infers the base from standard
prefixes like 0x, 0b, 0o). The resulting integer will always be a standard base-10 Python
integer.
Examples:

Output

Unit II continued…..
Text and File Handling:

Text File Handling: Reading and writing text files, Writing/Reading numbers as strings, File
modes

1. Explain file handling in Python with reference to reading a file. Describe read(),
readline(), and readlines() with examples.
2. Write a Python program to read the contents of a text file and display it.
3. Explain different methods used to read data from a file in Python.
4. Explain file handling in Python. Describe writing to a file, writelines(), appending data,
and closing a file with examples.
5. Write a Python program to store employee details in a text file using write and append
modes.
6. Describe different file modes used in Python for writing data to a file.

Reading and Writing to text files in Python

Python provides built-in functions for creating, writing and reading files. Two types of files can
be handled in Python, normal text files and binary files (written in binary format, 0s and 1s).

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 10
• Text files: Each line of text is terminated with a special character called EOL (End of
Line), which is new line character ('\n') in Python by default.

• Binary files: There is no terminator for a line and data is stored after converting it into
machine-understandable binary format.

Following topics cover opening, closing, reading and writing data in a text file.

Open Text File

It is done using open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

Example:

[Link]

[Link]

[Link]

# Open [Link] in append mode


file1 = open("[Link]", "a")

# Open [Link] in D:\Text with write+ mode


file2 = open(r"e:\python\[Link]", "w+")

r = raw string
Prevents backslash escape problems

Read Text File

There are three ways to read txt file.

1. Using read()

read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the
entire file.

File_object.read([n])

2. Using readline()

readline(): Reads one line of the file and returns in form of a string. For specified n, reads at
most n bytes. However, does not reads more than one line, even if n exceeds the length of the
line.

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 11
File_object.readline([n])

3. Using readlines()

readlines(): Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

Note: '\n' is treated as a special character of two bytes.

Example:

output

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 12
Write to Text File

There are two ways to write in a file:

1. Using write()

write(): Inserts the string str1 in a single line in the text file.

SYNTAX: File_object.write(str1)

OUTPUT:

Write to a text file

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 13
Writing to a text file means storing data in a file using write mode ("w").
If the file already exists, its previous contents are deleted.
Syntax
file = open("[Link]", "w")
[Link]("text to write")

writelines()
writelines() is used to write multiple strings to a file at once.
Each string must contain \n to move to a new line.

Syntax
file = open("[Link]", "w")
[Link](list_of_strings)

Example
[Link](["A\n", "B\n", "C\n"])

Append to a file
Appending to a file means adding data at the end of an existing file using append mode ("a"),
without deleting existing content.

Syntax
file = open("[Link]", "a")
[Link]("text to append")

Close the file


Closing a file saves all changes and releases system resources.
It is necessary to close a file after performing file operations.

Syntax
[Link]()

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 14
Output

Python close() function closes file and frees memory space acquired by that file. It is used at the
time when file is no longer needed or if it is to be opened in a different file mode.

File_object.close()

file1 = open("[Link]","a")

[Link]()

When working with files in Python, the file mode tells Python what kind of operations (read,
write, etc.) you want to perform on the file. You specify the mode as the second argument to the
open() function.

Different File Mode in Python

When working with files in Python, the file mode tells Python what kind of operations (read,
write, etc.) you want to perform on the file. You specify the mode as the second argument to the
open() function.

Below are the different types of file modes in Python along with their description:

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 15
Mode Description

‘r’ Read-only. Raises I/O error if file doesn't exist.

‘r+’ Read and write. Raises I/O error if the file does not exist.

‘w’ Write-only. Overwrites file if it exists, else creates a new one.

‘w+’ Read and write. Overwrites file or creates new one.

‘a’ Append-only. Adds data to end. Creates file if it doesn't exist.

‘a+’ Read and append. Pointer at end. Creates file if it doesn't exist.

‘rb’ Read in binary mode. File must exist.

‘rb+’ Read and write in binary mode. File must exist.

‘wb’ Write in binary. Overwrites or creates new.

‘wb+’ Read and write in binary. Overwrites or creates new.

‘ab’ Append in binary. Creates file if not exist.

‘ab+’ Read and append in binary. Creates file if it does not exist.

1. Read Mode ('r')

This mode allows you to open a file for reading only. If the file does not exist, it will raise
a FileNotFoundError.

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 16
Example: In this example, a file named '[Link]' is opened in read mode ('r'), and its content
is read and stored in the variable 'content' using a 'with' statement, ensuring proper resource
management by automatically closing the file after use.

with open('[Link]', 'r') as file:

content = [Link]()

Output:

Hello Geeks

2. Write Mode ('w')

Opens the file for writing only. If the file exists, its content is deleted. If not, a new file is
created.

Example: In this example, a file named '[Link]' is opened in write mode ('w'), and the
string 'Hello, world!' is written into the file.

with open('[Link]', 'w') as file:

[Link]('Hello, world!')

Output (file content after writing):

Hello, world!

Note: If you were to open the file "[Link]" after running this code, you would find that it
contains the text "Hello, world!" as the previous content "Hello Geeks" will be deleted.

3. Append Mode ('a')

Opens the file to add content at the end without deleting existing data. If the file doesn’t exist, it
creates a new one.

Example: In this example, a file named '[Link]' is opened in append mode ('a'), and the
string '\n This is a new line.' is written to the end of the file.

with open('[Link]', 'a') as file:

[Link]('\nThis is a new line.')

Output:

Hello, World!
This is a new line

The code will then write the string "\nThis is a new line." to the file, appending it to the
existing content or creating a new line if the file is empty.

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 17
4. Binary Mode ('b')

Used for non-text files like images or audio. Always combined with 'r', 'w', or 'a

Example: In this example, a file named '[Link]' is opened in binary read mode ('rb'). The
binary data is read from the file using the 'read()' method and stored in the variable 'data'.

with open('[Link]', 'rb') as file:

data = [Link]()

# Process the binary data

5. Read and Write Mode ('r+')

Opens the file for both reading and writing. Starts at the beginning of the file.
Raises FileNotFoundError if the file doesn’t exist.

with open('[Link]', 'r+') as file:

content = [Link]()

[Link]('\nThis is a new line.')

Output: If the initial contents of "[Link]" were:

Hello, World!
This is a new line

After running the code, the new content of the file would be:

This is a new line


Hello, World!
This is a new line

6. Write and Read Mode ('w+')

This mode allows you to open a file for both reading and writing. If the file already exists, it will
truncate the file to zero length. If the file does not exist, it will create a new file.

Example: In this example, a file named '[Link]' is opened in write and read mode ('w+').

with open('[Link]', 'w+') as file:

[Link]('Hello, world!')

[Link](0)

content = [Link]()

Output:

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 18
Hello, world!

Explanation: the output of this code is "Hello, world!". Since the file was truncated and the
pointer was moved to the beginning before reading, the contents of the file will be exactly what
was written to it. So, content will contain the string "Hello, world!".

PYTHON Programming UNIT2 NOTES (Strings Handling) 3MCA A and D Faculty: Ms. Anitha Page 19

[Link]

You might also like