Module 9

A simple FASTA parser

Building a reusable parser.

A parser function

You can write a function that takes a FASTA string and returns a list of (header, sequence) pairs.

Python
def parse_fasta(text):
    results = []
    for block in text.split(">")[1:]:
        lines = block.strip().split("\n")
        header = lines[0]
        sequence = "".join(lines[1:])
        results.append((header, sequence))
    return results

fasta = ">Tv01\nATGC\n>Tv02\nGGGG"
print(parse_fasta(fasta))
[('Tv01', 'ATGC'), ('Tv02', 'GGGG')]
Your task

FASTA parser function

  • Write parse_fasta(text) and test it.