Back to List

Python Strings and File I/O

Learn the basics of slicing and concatenating strings, and reading and writing files in Python.

Beginner
|
8min
|
Verified (2026-07)
string manipulationfile input/outputopenwith statementf-string
Progress0/18 (0%)

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.

python
text = "BioPlayground"
print(text[0]) # 'B' β€” first character
print(text[-1]) # 'd' β€” last character
print(text[3:7]) # 'Play' β€” from index 3 to 6
print(len(text)) # 13

Strings are immutable. text[0] = 'b' will cause an error. To modify a string, you must create a new string.


Commonly used string methods

python
msg = " Hello, World! "
msg.strip() # 'Hello, World!' β€” removes leading and trailing whitespace
msg.lower() # ' hello, world! '
msg.upper() # ' HELLO, WORLD! '
msg.replace("World", "Python") # ' Hello, Python! '
# Splitting and joining
csv = "apple,banana,grape"
fruits = csv.split(",") # ['apple', 'banana', 'grape']
"-".join(fruits) # 'apple-banana-grape'
# Checking for inclusion
"banana" in csv # True
csv.startswith("apple") # True
csv.count(",") # 2

split() 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.

python
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 possible
print(f"Pass or fail: {'Pass' if score >= 60 else 'Fail'}")
# Pass or fail: Pass
# Floating-point formatting
pi = 3.141592
print(f"Pi: {pi:.2f}") # Pi: 3.14

Older methods ("% s" % name, "{}" .format(name)) also work, but f-strings are superior in both readability and performance.


Reading files

python
# Read the entire file
with 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 character

The 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

python
# 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 file
with open("output.txt", "a", encoding="utf-8") as f:
f.write("Appended line\n")
ModeMeaningBehavior if file does not exist
"r"Read-onlyError
"w"Write (overwrite)Create new file
"a"AppendCreate new file
"x"Create (error if file exists)Create new file

Practical pattern β€” Parsing CSV directly

python
# 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.


πŸ’¬ Questions & Comments

0 comments

You can post without signing in. Guest comments cannot be edited or deleted by their author.

0/2000

Loading...