Python Strings and File Input/Output
After completing this topic
You will be able to manipulate strings in various ways using Python and read and write text files.
Strings are sequences of characters
In Python, a string (str) is a sequence of characters arranged in order. Like lists, they can be indexed and sliced.
text = "BioPlayground"
print(text[0]) # 'B' β first characterprint(text[-1]) # 'd' β last characterprint(text[3:7]) # 'Play' β from index 3 to 6print(len(text)) # 13Strings are immutable. text[0] = 'b' will cause an error. To modify a string, you must create a new string.
Commonly used string methods
msg = " Hello, World! "
msg.strip() # 'Hello, World!' β removes leading and trailing whitespacemsg.lower() # ' hello, world! 'msg.upper() # ' HELLO, WORLD! 'msg.replace("World", "Python") # ' Hello, Python! '
# Splitting and joiningcsv = "apple,banana,grape"fruits = csv.split(",") # ['apple', 'banana', 'grape']"-".join(fruits) # 'apple-banana-grape'
# Checking for inclusion"banana" in csv # Truecsv.startswith("apple") # Truecsv.count(",") # 2split() and join() are used daily in CSV parsing, log analysis, and data preprocessing.
f-strings β Inserting variables into strings
Introduced in Python 3.6, f-strings are the cleanest way to insert variables directly into strings.
name = "Kim Hoon"score = 95.5
# f-string (recommended)print(f"{name}'s score: {score} points")# Kim Hoon's score: 95.5 points
# Expressions are also possibleprint(f"Pass or fail: {'Pass' if score >= 60 else 'Fail'}")# Pass or fail: Pass
# Floating-point formattingpi = 3.141592print(f"Pi: {pi:.2f}") # Pi: 3.14Older methods ("% s" % name, "{}" .format(name)) also work, but f-strings are superior in both readability and performance.
Reading files
# Read the entire filewith open("data.txt", "r", encoding="utf-8") as f: content = f.read() print(content)
# Read line by line (better for large files)with open("data.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip()) # Remove newline characterThe with statement opens a file and automatically closes it when the block is finished. You do not need to call f.close() explicitly. If you do not use with, the file may not be closed, which can lead to memory leaks. Always use with.
Writing to files
# Create a new file (overwrites existing content)with open("output.txt", "w", encoding="utf-8") as f: f.write("First line\n") f.write("Second line\n")
# Append to an existing filewith open("output.txt", "a", encoding="utf-8") as f: f.write("Appended line\n")| Mode | Meaning | Behavior if file does not exist |
|---|---|---|
"r" | Read-only | Error |
"w" | Write (overwrite) | Create new file |
"a" | Append | Create new file |
"x" | Create (error if file exists) | Create new file |
Practical pattern β Parsing CSV directly
# Parse a CSV file directly (without libraries)with open("scores.csv", "r", encoding="utf-8") as f: header = f.readline().strip().split(",") print(header) # ['Name', 'Korean', 'English', 'Math'] for line in f: fields = line.strip().split(",") name = fields[0] total = sum(int(x) for x in fields[1:]) print(f"{name}: Total score {total}")Of course, in real-world applications, you would use the csv module or pandas, but understanding the principles of file input/output allows you to handle any type of data.
Key takeaways
Strings and files are the input/output channels of programming. All processes of reading external data, processing results, and outputting them in a human-readable format begin here. split, join, f-string, with open β mastering these four will enable you to handle most text processing tasks.