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.
A line is read in as line = "S001,72,M". What does line.split(",") return?
After parts = "S001,72,M".split(","), what is the type of parts[1]?
What does " hello ".strip() return?
What does "banana".strip("an") return?
You want to pick out file names that start with either "GTEX_" or "TCGA_". Which call does that in one line?
raw = " P001 ". You run raw.strip() on its own line (no assignment), then print(repr(raw)). What is printed?
What does "A-A-A".replace("A", "T") return?
What does ",".join(["S001", "72", "M"]) return?
I can split a comma-separated line into a list of fields and pull out each field by index.
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.
I can use startswith() with a tuple of prefixes to filter a list of file names by project.
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.
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.

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
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 this snippet in the Python Scratchpad on the right.
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 strConvert 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.8Fix the same kind of mistake in the exercise below.
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.
record = "S001,72,M"
parts = record.split(",")
age = parts[1]
years_to_60 = 60 - age
print(years_to_60)
- Convert the age piece to an integer before subtracting: age = int(parts[1]) ★
- Cast the 60 to a string so both sides are strings: years_to_60 = str(60) - age
- Wrap the whole subtraction in int() to coerce the result: years_to_60 = int(60 - age)
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.8Type the code below into the Python Scratchpad and run it.
Try this snippet in the Python Scratchpad on the right.
line = "S001,72,M"
pid, age_str, sex = line.split(",")
age = int(age_str)
print(pid, age + 1, sex)
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 ") # FalseThe 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]
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.
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.
records = [" P001", "P002 ", " P003 "]
genotypes = {"P001": "AA", "P002": "AG", "P003": "GG"}
for record in records:
print(genotypes[record])
- Strip whitespace from both ends before the lookup: print(genotypes[record.strip()]) ★
- Strip only the leading whitespace: print(genotypes[record.lstrip()])
- Slice off the first and last character: print(genotypes[record[1:-1]])
Now type the corrected code into the Python Scratchpad and run it.
Try this snippet in the Python Scratchpad on the right.
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.8The 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")) # reporTry this snippet in the Python Scratchpad on the right.
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 this snippet in the Python Scratchpad on the right.
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]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_")) # FalseYou 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
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 this snippet in the Python Scratchpad on the right.
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"))) # TrueSo 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.
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
The call is some_string.replace(old, new). As with every string method, you assign the result to a variable to keep it.
Try this snippet in the Python Scratchpad on the right.
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", "")) # reportsThe 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 this snippet in the Python Scratchpad on the right.
raw = "AAA-AAA-AAA"
raw.replace("A", "T")
raw.replace("A", "T", 2)
note = "none reported"
note.replace("none", "missing")
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, NgThe 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 foundTry this snippet in the Python Scratchpad on the right.
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.9The 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.
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.
A line is read in as line = "S001,72,M". What does line.split(",") return?
After parts = "S001,72,M".split(","), what is the type of parts[1]?
What does " hello ".strip() return?
What does "banana".strip("an") return?
You want to pick out file names that start with either "GTEX_" or "TCGA_". Which call does that in one line?
raw = " P001 ". You run raw.strip() on its own line (no assignment), then print(repr(raw)). What is printed?
What does "A-A-A".replace("A", "T") return?
What does ",".join(["S001", "72", "M"]) return?
I can split a comma-separated line into a list of fields and pull out each field by index.
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.
I can use startswith() with a tuple of prefixes to filter a list of file names by project.
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.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?