DEV Community

Cover image for Python- String Methods and File Handling
Mary Ngure
Mary Ngure

Posted on

Python- String Methods and File Handling

Two things you'll do constantly in almost any Python program are working with text and working with files - cleaning up user input, formatting output, or reading and writing data to disk.

Part 1: String Methods

Strings in Python come with a large set of built-in methods for inspecting, cleaning, and transforming text.
None of these methods change the original string - strings are immutable, so every method returns a new string.

Changing case

name = "Mary Wanjiku"

print(name.upper())       # MARY WANJIKU
print(name.lower())       # mary wanjiku
print(name.title())       # Mary Wanjiku
print(name.capitalize())  # Mary wanjiku
Enter fullscreen mode Exit fullscreen mode

Removing whitespace

.strip() removes leading and trailing whitespace - useful when cleaning up user input or data read from a file.

raw_input = "   mary@example.com   "
cleaned = raw_input.strip()
print(f"'{cleaned}'")  # 'mary@example.com'

print("  hello".lstrip())  # "hello" (left only)
print("hello  ".rstrip())  # "hello" (right only)
Enter fullscreen mode Exit fullscreen mode

Searching and checking content

text = "Data Analyst - Nairobi"

print(text.startswith("Data"))   # True
print(text.endswith("Nairobi"))  # True
print("Analyst" in text)         # True
print(text.find("Nairobi"))      # 14 (index where it starts)
print(text.find("Manager"))      # -1 (not found)
Enter fullscreen mode Exit fullscreen mode

Splitting and joining

.split() breaks a string into a list; .join() does the reverse.

csv_row = "Mary,Data Analyst,Nairobi"
fields = csv_row.split(",")
print(fields)  # ['Mary', 'Data Analyst', 'Nairobi']

words = ["Python", "is", "fun"]
sentence = " ".join(words)
print(sentence)  # Python is fun
Enter fullscreen mode Exit fullscreen mode

Checking the content type of a string

Python has several methods that check what kind of characters a string contains, returning True or False. These are especially useful for validating input.

print("12345".isdigit())     # True  -> all characters are digits
print("Hello".isdigit())     # False

print("Hello".isalpha())     # True  -> all characters are letters
print("Hello123".isalpha())  # False -> contains digits

print("Hello123".isalnum())  # True  -> all characters are letters or digits
print("Hello 123".isalnum()) # False -> contains a space

print("   ".isspace())       # True  -> all characters are whitespace
print("  a ".isspace())      # False -> contains a non-space character
Enter fullscreen mode Exit fullscreen mode

A practical use for these is validating simple user input before processing it:

user_input = "A1234"

if user_input.isalnum():
    print("Valid: letters and numbers only")
else:
    print("Invalid: contains other characters")
Enter fullscreen mode Exit fullscreen mode

Counting occurrences

.count() tells you how many times a substring appears in a string:

text = "data analyst, data engineer, data scientist"
print(text.count("data"))      # 3
print(text.count("engineer"))  # 1
Enter fullscreen mode Exit fullscreen mode

Replacing text

message = "Hello World"
print(message.replace("World", "Python"))  # Hello Python
Enter fullscreen mode Exit fullscreen mode

Formatting strings

f-strings are the modern, readable way to build strings that include variable values:

name = "Mary"
role = "Data Analyst"
print(f"{name} works as a {role}.")  # Mary works as a Data Analyst.

price = 1234.5
print(f"Total: ${price:.2f}")  # Total: $1234.50
Enter fullscreen mode Exit fullscreen mode

Practical example: cleaning a list of raw entries

raw_entries = ["  MARY  ", "james ", " Ali", "GRACE"]

cleaned_entries = [entry.strip().title() for entry in raw_entries]
print(cleaned_entries)  # ['Mary', 'James', 'Ali', 'Grace']
Enter fullscreen mode Exit fullscreen mode

This kind of cleanup — stripping whitespace and standardizing case — comes up constantly when working with messy, real-world text data.

Part 2: File Handling

File handling lets your program read from and write to files on disk, so data can persist beyond a single run of the program.

Opening a file

The open() function opens a file and returns a file object. The most common modes are:

Mode Meaning
"r" Read (default) — file must exist
"w" Write — creates the file, overwrites if it exists
"a" Append — adds to the end of the file
"r+" Read and write

Using with to handle files safely

The recommended way to work with files is the with statement, because it automatically closes the file for you, even if an error occurs partway through:

with open("notes.txt", "w") as file:
    file.write("This is my first line.\n")
    file.write("This is my second line.\n")
Enter fullscreen mode Exit fullscreen mode

Once the with block ends, the file is closed automatically — no need to call file.close() yourself.

Reading a file

with open("notes.txt", "r") as file:
    content = file.read()
print(content)
# This is my first line.
# This is my second line.
Enter fullscreen mode Exit fullscreen mode

Reading line by line

For larger files, reading line by line is more memory-efficient than loading the whole file at once:

with open("notes.txt", "r") as file:
    for line in file:
        print(line.strip())  # .strip() removes the trailing newline
Enter fullscreen mode Exit fullscreen mode

You can also get all lines as a list with .readlines():

with open("notes.txt", "r") as file:
    lines = file.readlines()
print(lines)  # ['This is my first line.\n', 'This is my second line.\n']
Enter fullscreen mode Exit fullscreen mode

Appending to a file