TheAlgorithms/Python · error · ValueError

Invalid Strand

Error message

Invalid Strand

What it means

Raised by the dna complement function in strings/dna.py when the input strand contains any character outside the DNA alphabet A, T, C, G. The function computes the complement by counting regex matches of [ATCG] and comparing to the strand length; any mismatch (lowercase letters, U for RNA, N, whitespace, digits) means the input is not a valid DNA strand and ValueError('Invalid Strand') is raised before the translate step.

Source

Thrown at strings/dna.py:22

def dna(dna: str) -> str:
    """
    https://en.wikipedia.org/wiki/DNA
    Returns the second side of a DNA strand

    >>> dna("GCTA")
    'CGAT'
    >>> dna("ATGC")
    'TACG'
    >>> dna("CTGA")
    'GACT'
    >>> dna("GFGG")
    Traceback (most recent call last):
        ...
    ValueError: Invalid Strand
    """

    if len(re.findall("[ATCG]", dna)) != len(dna):
        raise ValueError("Invalid Strand")

    return dna.translate(dna.maketrans("ATCG", "TAGC"))


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Normalize before calling: dna(strand.strip().upper()) handles whitespace and case.
  2. Convert RNA to DNA if that is the intent: strand.replace('U', 'T').
  3. Filter or reject ambiguity codes: if set(strand) - set('ATCG'): raise/report bad record.

Example fix

# before
dna(line)  # line = 'atgc\n' -> ValueError: Invalid Strand

# after
dna(line.strip().upper())
Defensive patterns

Strategy: validation

Validate before calling

strand = strand.strip().upper()
if set(strand) - set('ATCG'):
    raise ValueError(f'invalid DNA characters: {set(strand) - set("ATCG")}')
complement = dna(strand)

Type guard

def is_dna_strand(s: str) -> bool:
    return isinstance(s, str) and not set(s.upper()) - set('ATCG')

Try / catch

try:
    comp = dna(strand)
except ValueError:
    comp = dna(strand.strip().upper().replace('U', 'T'))  # tolerate RNA/case/whitespace

Prevention

When it happens

Trigger: dna('GFGG'); dna('atgc') (lowercase fails the regex); dna('AUCG') (RNA U fails); dna('ATGC ') (trailing space); dna('ATG1').

Common situations: Reading FASTA/sequence files without stripping newlines and headers; case-inconsistent data from databases; accidentally passing RNA strands or sequences with ambiguity codes (N, R, Y).

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/9fa41361875287b9. Report an issue: GitHub.