Difficulty: Beginner to Intermediate | Prerequisites: Lists, basic loop syntax
Strings and file I/O round out the built-in types covered in this unit. Strings are immutable sequences of characters that support many of the same operations as lists and tuples (indexing, slicing, iteration) but come with their own set of methods for text processing. File I/O is how your programs read data from and write data to files on disk, which is essential once you move beyond hard-coded values.
Strings are immutable sequences of characters that support indexing, slicing, and a rich set of text-processing methods (splitting, joining, case conversion, character-type checks). File I/O lets your programs open files on disk to read, write, or append data using a simple open-process-close pattern. Both topics build on the sequence and iteration concepts from lists and tuples.
String
A built-in, immutable Python sequence of characters. Written with single or double quotes: "hello" or 'hello'.
Think of it as a fixed row of characters you can read and search through but cannot change in place.
File object
The object returned by open(filename, mode). You interact with the file on disk through this object (reading, writing, closing).
Think of it as a handle or remote control for a file: you give Python the filename, and it hands you back the remote.
File mode
A string passed to open() that determines what you can do with the file. 'r' for reading, 'w' for writing (overwrites existing content), 'a' for appending (adds to the end).
In simple terms, the mode tells Python whether you want to read the file, start it fresh, or add to what is already there.
str.strip()
Returns a copy of the string with leading and trailing whitespace removed (or specified characters, if provided).
In simple terms, it trims the blank space off both ends of the string.
str.split()
Breaks a string into a list of substrings, splitting at a specified delimiter (defaults to whitespace).
Think of it as cutting a sentence into individual words.
str.join()
Concatenates an iterable of strings, placing the calling string between each element. For example, ", ".join(["a", "b", "c"]) produces "a, b, c".
Think of it as gluing a list of words back together with a separator of your choice.
Built-in Python type, a sequence of characters
Immutable: you cannot change a character at an index after creation (my_str[0] = "H" raises a TypeError)
Iterable: you can loop over the characters with for-each or index-based loops
Indexing (read-only): my_str[0] returns the first character
Slicing: my_str[1:4] returns a substring
+ operator: concatenates strings ("hello" + " world" gives "hello world")
* operator: repeats a string ("ha" * 3 gives "hahaha")
in operator: "lo" in "hello" evaluates to True
Iteration with for-each and index-based for loops
str.strip([chars]) : removes leading and trailing characters (defaults to whitespace)
str.split(sep) : returns a list of substrings split at the delimiter sep. Defaults to whitespace. Note: consecutive delimiters with an explicit sep produce empty strings in the result; with whitespace default, they do not.
str.join(iterable) : joins an iterable of strings with str as the separator
str.lower() : returns a copy with all letters lowercase
str.upper() : returns a copy with all letters uppercase
str.isalpha() : returns True if all characters are alphabetic
str.isdigit() : returns True if all characters are digits
str.isspace() : returns True if all characters are whitespace
string module)string.ascii_lowercase : the lowercase alphabet
string.digits : the digit characters '0123456789'
string.punctuation : common punctuation characters
Open a file with file_variable = open(filename, mode)
filename is a string (the file's name or path)
mode is a string: 'r' (read), 'w' (write), 'a' (append)
Always close the file when finished: file_variable.close()
Failing to close a file after writing can result in data loss
Closing also prevents multiple open handles from overwriting each other
'w' mode)Opens the file for writing. If the file does not exist, Python creates it. If the file already exists, its contents are erased.
Write with file_variable.write(string), where string is a string literal or a variable holding a string
The write() method does not add a newline automatically; include \n if you want line breaks
'a' mode)Opens the file for appending. Preserves existing content and adds new data to the end.
Uses the same file_variable.write(string) method as write mode
'r' mode)file_variable.read() : returns the entire file's contents as a single string. You can pass an integer to read only that many characters.
file_variable.readlines() : returns a list of strings, one per line (each string includes the trailing \n)
file_variable.readline() : returns a single line (up to and including the newline character)
Method 1: while loop with readline()
line = file_variable.readline()
while line != "": then process line, then line = file_variable.readline() again
Method 2: for loop over the file object
for var in file_variable: then process var
This is the cleaner, more Pythonic approach
Students often try to modify a string character by index (e.g. my_str[0] = "H"). This does not work. Strings are immutable. Build a new string instead.
Students frequently forget that 'w' mode erases the existing file contents. If you want to add to a file without losing what is already there, use 'a' mode.
Students sometimes expect split() with an explicit delimiter and split() with no argument to behave identically on repeated whitespace. They do not: "a b".split(" ") produces ["a", "", "b"] (with an empty string), while "a b".split() produces ["a", "b"].
Students often forget to close files after writing. This is a real source of bugs: data may not be flushed to disk until close() is called.
⚠️ Know the difference between read(), readline(), and readlines(). Exams often ask what type each returns (string vs list of strings).
⚠️ Understand the distinction between 'w' and 'a' modes. A question might ask what happens to existing file contents when you open with 'w'.
⚠️ String methods return new strings; they do not modify the original. If you write my_str.upper() without assigning the result, the original string is unchanged.
⚠️ Be comfortable chaining strip() and split() together. A common file-processing pattern is line.strip().split(",") to clean and parse CSV-like data.
True or False: You can change a character in a string by assigning to its index.
False. Strings are immutable.
Fill in the blank: To open a file for reading, you pass the mode ___ to open().
'r'.
True or False: file.readlines() returns a single string containing the entire file.
False. It returns a list of strings, one per line.
Fill in the blank: "hello world".split() returns ___.
["hello", "world"].
True or False: Opening a file in 'w' mode preserves its existing contents.
False. 'w' mode erases the file's existing contents.
Q: What does "banana".split("a") return?
A: ["b", "n", "n", ""]. The string is split at each "a", and the trailing "a" produces an empty string at the end.
Q: You want to read a file called data.txt and print each line without trailing whitespace. Write the code.
A: f = open("data.txt", "r") then for line in f: then print(line.strip()) then f.close()
Q: What is the difference between file.read() and file.readlines()?
A: read() returns the entire file as a single string. readlines() returns a list of strings, one for each line in the file.
Q: What does " ".join(["a", "b", "c"]) produce?
A: "a b c". The space character is placed between each element of the list.
Q: A student opens a file with open("log.txt", "w") and writes some data. They then open it again with open("log.txt", "a") and write more. What does the file contain?
A: Only the data from the second write would be appended to the data from the first. The first open with 'w' erased any previous contents and wrote the first batch. The second open with 'a' preserved the first batch and added the second batch to the end.
Strings behave like immutable sequences, so everything you learned about tuples (indexing, slicing, iteration, no in-place modification) applies to strings as well. The main addition is the rich set of text-processing methods.
File I/O ties directly to dictionaries and lists: a common exam pattern is reading data from a file, parsing each line with strip() and split(), and storing the results in a list or dictionary for further processing.
The in operator works on strings the same way it works on lists, tuples, and sets, but it checks for substrings rather than individual elements.
Python string, str methods, string immutability, str.split(), str.join(), str.strip(), str.lower(), str.upper(), isalpha, isdigit, isspace, file I/O, open(), read(), readline(), readlines(), write(), file modes, append mode, read mode, write mode, file.close(), text processing, CSV parsing, string constants, string module, CS 303E, intro to programming, Python data structures