1. Strings and Text Files
1.1 String Basics
- A string is a sequence of characters (immutable).
- Subscript operator
[]is used to access characters.
- Example:
s[2]returns the third character.
- Example:
- Slicing:
s[start:end]returns a substring. inoperator checks for substring presence.
1.2 String Methods
- Strings have methods like
.upper(),.lower(),.find(),.split(),.replace().
Strings are immutable: operations return new strings.
s = “sample”
s.upper() # returns ‘SAMPLE’
print(s) # still 'sample's = s.upper() # now s = ‘SAMPLE’
1.3 Text File Handling
Writing:
with open("filename.txt", 'w') as f:f.write(“Line 1\nLine 2”)
- Always convert non-string data (e.g., integers) using
str()before writing.
Reading:
with open("filename.txt", 'r') as f:text = f.read() # or f.readline(), or use a loop
Reading Numbers:
with open("integers.txt", 'r') as f:
for line in f:sum += int(line.strip())
CSV Files:
import csv
with open("file.csv", 'w', newline='') as f:writer = csv.writer(f)
writer.writerow([“Item”, “Brand”, 1000])