Section 1

1 Before you start

This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.

Pre-test

A line is read in as line = "S001,72,M". What does line.split(",") return?

Pre-test

After parts = "S001,72,M".split(","), what is the type of parts[1]?

Pre-test

What does " hello ".strip() return?

Pre-test

What does "banana".strip("an") return?

Pre-test

You want to pick out file names that start with either "GTEX_" or "TCGA_". Which call does that in one line?

Pre-test

raw = " P001 ". You run raw.strip() on its own line (no assignment), then print(repr(raw)). What is printed?

Pre-test

What does "A-A-A".replace("A", "T") return?

Pre-test

What does ",".join(["S001", "72", "M"]) return?

Pre-confidence

I can split a comma-separated line into a list of fields and pull out each field by index.

Not at all confident
Fully confident
Pre-confidence

I can clean stray whitespace off the ends of a string with strip(), and explain why I have to assign the result back to a variable.

Not at all confident
Fully confident
Pre-confidence

I can use startswith() with a tuple of prefixes to filter a list of file names by project.

Not at all confident
Fully confident
Section 2

2 Introduction

Much of the data in precision health and medicine is stored as text. In this lesson, you will cut a line of text into pieces, clean each piece and put the pieces back together into one line.

This lesson covers five string methods: split, strip, startswith, replace and join. Each method does one small job. At the end of the lesson, you will use all five methods to clean a short list of results.

Try every example in the Python Scratchpad on the right.

Section 3

3 String methods (split, strip, startswith, replace)

A patient name, a ward and a line read from a file are all strings. Text that a person types is often messy. So you usually need to clean the text before you can use the data. Here is one line that a colleague typed by hand. It holds a patient name, a ward and a potassium result:

entry = "  Kumar, 5A, 5.8 mmol/L "
print("[" + entry + "]")  # [  Kumar, 5A, 5.8 mmol/L ]

The square brackets show where the string starts and ends. Commas separate the three values. There are extra spaces around the values. And the potassium result has its unit after it.

The string methods in this lesson turn this line into three clean values. The picture below shows four of them at work.

Four string methods turn messy real-world health text into something computable, and each returns a specific kind of result.
Four string methods turn messy real-world health text into something computable, and each returns a specific kind of result.
Section 3.1

3.1 Split

A line read from a CSV file is one long string, such as "Kumar,5A,5.8". This string holds three values. The string method split cuts a string at each comma and gives back a list of pieces:

entry = "Kumar,5A,5.8"
fields = entry.split(",")
print(fields)  # ['Kumar', '5A', '5.8']
print(fields[0])  # Kumar
Splitting strings into a list.
Splitting strings into a list.

In the call entry.split(","), entry is the string and split is the method. The separator is the text where the string is cut. It goes inside the round brackets. The separator is also a string. So the comma is written inside quote marks. You can take any list item by its index, such as fields[0].

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
line = "S001,72,M"
parts = line.split(",")
print(parts)

Every list item is a string, even when it looks like a number. This is because split only cuts the text. So Python cannot add a number to the potassium result:

fields = "Kumar,5A,5.8".split(",")
print(fields[2] + 1)
# TypeError: can only concatenate str (not "int") to str

Convert the item with float() before you use it as a number:

fields = "Kumar,5A,5.8".split(",")
potassium = float(fields[2])
print(potassium + 1)  # 6.8

Fix the same kind of mistake in the exercise below.

Debug & fix

The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

Broken code (do not copy verbatim)
record = "S001,72,M"
parts = record.split(",")
age = parts[1]
years_to_60 = 60 - age
print(years_to_60)

As with a tuple, you can unpack the list into separate names. You need one name for each piece. Python gives the pieces to the names in order:

name, ward, potassium = "Kumar,5A,5.8".split(",")
print(name)  # Kumar
print(ward)  # 5A
print(potassium)  # 5.8

Type the code below into the Python Scratchpad and run it.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
line = "S001,72,M"
pid, age_str, sex = line.split(",")

age = int(age_str)
print(pid, age + 1, sex)
Section 3.2

3.2 strip

Text a person types often has spaces at its start or end. You cannot see these spaces when the text is printed. But to Python, a space is a character like any other character. So "Kumar " with a space after it is not equal to "Kumar":

print("Kumar" == "Kumar ")  # False

The string method strip removes these spaces. It gives back the string without spaces, tabs and newline characters at its start and end. So the comparison now gives True:

print("Kumar" == "Kumar ".strip())  # True
print("[" + "  Ward 5A  ".strip() + "]")  # [Ward 5A]
Different variations of strip methods.
Different variations of strip methods.

The call is some_string.strip(). The spaces inside the string are kept. For example, the space between Ward and 5A stays where it is.

Fix the exercise below. Some of the patient IDs have spaces around them.

Debug & fix

The code below is broken. Type a fixed version into the editor, then click Run & check. Success means your code runs without errors and produces output. Use Show hint only if you get stuck.

Broken code (do not copy verbatim)
records = [" P001", "P002 ", "  P003  "]
genotypes = {"P001": "AA", "P002": "AG", "P003": "GG"}
for record in records:
    print(genotypes[record])

Now type the corrected code into the Python Scratchpad and run it.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
records = [" P001", "P002 ", "  P003  "]
genotypes = {"P001": "AA", "P002": "AG", "P003": "GG"}
for record in records:
    print(genotypes[record.strip()])

There are two variations of strip.

First, you can choose which characters strip removes. You write them as a string inside the round brackets. For example, a laboratory system may put a star on each side of a high result. With a star as the argument, strip removes the stars:

result = "*5.8*"
print(result.strip("*"))  # 5.8

The method strip can remove more than you expect. The next example tries to remove the ending .tsv from a file name. The letters s and t at the end of reports are also in the set. So strip removes them too:

print("reports.tsv".strip(".tsv"))  # repor
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
header = "###Gene: BRCA1###"
print(header.strip("#"))
brackets = "[[APOE]]"
print(brackets.strip("[]"))
flanked = "ATATCGATCGATAT"
print(flanked.strip("AT"))

Second, lstrip() removes spaces only from the left end. And rstrip() removes spaces only from the right end:

ward = "  Ward 5A  "
print("[" + ward.lstrip() + "]")  # [Ward 5A  ]
print("[" + ward.rstrip() + "]")  # [  Ward 5A]
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
raw = " P001 "
print("[" + raw.lstrip() + "]")
print("[" + raw.rstrip() + "]")

Now look at what happens when a line calls strip and does not keep the result:

ward = "  Ward 5A  "
ward.strip()
print("[" + ward + "]")  # [  Ward 5A  ]
ward = ward.strip()
print("[" + ward + "]")  # [Ward 5A]
Section 3.3

3.3 startswith

The string method startswith checks how a string begins. It gives back True if the string begins with a given piece of text, called a prefix. Otherwise, it gives back False:

filename = "kidney_notes.txt"
print(filename.startswith("kidney_"))  # True
print(filename.startswith("heart_"))  # False

You can use startswith to pick some items out of a list. The loop below checks each file name. It prints only the names that begin with kidney_:

files = ["kidney_notes.txt", "heart_scan.csv", "kidney_ids.txt"]
for filename in files:
    if filename.startswith("kidney_"):
        print(filename)  # kidney_notes.txt, kidney_ids.txt
Searching using startswith.
Searching using startswith.

The call is some_string.startswith(prefix). The matching method endswith checks the end of a string in the same way. For example, "kidney_notes.txt".endswith(".txt") gives True.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
fname = "GTEX_blood_001.fastq"
if fname.startswith("GTEX_"):
    print("from GTEX project")

To check for more than one prefix, put the prefixes in a tuple. The method gives back True if the string begins with any one of them:

code = "rs12345"
print(code.startswith(("rs", "ss")))  # True

So there are two pairs of round brackets in code.startswith(("rs", "ss")). The outer pair belongs to the method call. The inner pair makes the tuple. If you leave out the inner pair, Python reads the second value as a start position and raises a TypeError.

Section 3.4

3.4 replace

The string method replace swaps one piece of text for another. It takes two arguments. The first argument is the text to look for. The second argument is the new text. For example, a file name cannot contain a slash. So a date written with slashes must be changed before it is used in a file name:

date = "22/10/2026"
print(date.replace("/", "-"))  # 22-10-2026
Replacing old string with new string.
Replacing old string with new string.

The call is some_string.replace(old, new). As with every string method, you assign the result to a variable to keep it.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
sex = "M"
sex = sex.replace("M", "Male")
print(sex)

The method replace swaps every match. For example, it swapped both slashes in the date above. To limit this, give a third argument, which is the number of matches to swap. You can also remove text. To do this, swap the text for an empty string, which is two quote marks with nothing between them:

date = "22/10/2026"
print(date.replace("/", "-", 1))  # 22-10/2026
result = "5.8 mmol/L"
print(result.replace(" mmol/L", ""))  # 5.8
print("reports.tsv".replace(".tsv", ""))  # reports

The method replace looks for the whole piece of text. So it removes .tsv correctly. The method strip removed too much from the same file name.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
raw = "AAA-AAA-AAA"
raw.replace("A", "T")
raw.replace("A", "T", 2)

note = "none reported"
note.replace("none", "missing")
Section 3.5

3.5 join: the inverse of split

The string method join does the opposite of split. It takes a list of strings and gives back one string:

flagged = ["Kumar", "Wong", "Ng"]
print(", ".join(flagged))  # Kumar, Wong, Ng

The call looks backwards at first. You write the separator first. Then you write a dot, the method name and the list inside round brackets. The separator goes only between the items. So there is no separator after the last item.

Every item in the list must be a string. The first print line below converts each number with str(). The second print line does not. So Python raises a TypeError:

levels = [5.8, 5.2, 6.1]
print(", ".join([str(level) for level in levels]))  # 5.8, 5.2, 6.1
print(", ".join(levels))
# TypeError: sequence item 0: expected str instance, float found
Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
parts = ["S001", "72", "M"]
line = "".join(parts)
print(line)

genes = ["APOE", "TREM2", "BIN1"]
print(" | ".join(genes))

ages = [54, 61, 47]
print(",".join(str(a) for a in ages))

Now use all five methods together. The list below holds four lines typed by hand. The first line is a note that begins with a hash sign. The other three lines each hold a name, a ward and a potassium result, with extra spaces and a unit:

entries = [
    "# potassium results, typed by hand",
    "  Kumar, 5A, 5.8 mmol/L ",
    "Ng ,5A,6.1 mmol/L",
    " Lim, 7B , 3.9 mmol/L",
]

for entry in entries:
    if entry.startswith("#"):
        continue
    entry = entry.replace(" mmol/L", "")
    fields = [field.strip() for field in entry.split(",")]
    print(", ".join(fields))  # Kumar, 5A, 5.8 / Ng, 5A, 6.1 / Lim, 7B, 3.9

The loop takes one line at a time. The method startswith checks for the hash sign. So continue skips the note. The method replace removes the unit. The method split cuts the line at each comma. The method strip removes extra spaces from each piece. And the method join puts the pieces back together.

Section 4

4 Check your understanding

You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.

Post-test

A line is read in as line = "S001,72,M". What does line.split(",") return?

Post-test

After parts = "S001,72,M".split(","), what is the type of parts[1]?

Post-test

What does " hello ".strip() return?

Post-test

What does "banana".strip("an") return?

Post-test

You want to pick out file names that start with either "GTEX_" or "TCGA_". Which call does that in one line?

Post-test

raw = " P001 ". You run raw.strip() on its own line (no assignment), then print(repr(raw)). What is printed?

Post-test

What does "A-A-A".replace("A", "T") return?

Post-test

What does ",".join(["S001", "72", "M"]) return?

Post-confidence

I can split a comma-separated line into a list of fields and pull out each field by index.

Not at all confident
Fully confident
Post-confidence

I can clean stray whitespace off the ends of a string with strip(), and explain why I have to assign the result back to a variable.

Not at all confident
Fully confident
Post-confidence

I can use startswith() with a tuple of prefixes to filter a list of file names by project.

Not at all confident
Fully confident
Section 5

5 Your results

Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.

Your score

Submit the post-test to see your results.

Muddiest point

What is the one thing from this module that is still unclear to you?

Rate this module

Overall, how would you rate this module?

How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)