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
- Normalize before calling: dna(strand.strip().upper()) handles whitespace and case.
- Convert RNA to DNA if that is the intent: strand.replace('U', 'T').
- 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
- Normalize sequence data early: strip newlines/whitespace and uppercase.
- Reject ambiguity codes (N, R, Y) explicitly so bad records are visible, not silent.
- If processing RNA, convert U to T before using this DNA complement function.
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
- '{i}' not in list of symbols
- Length of alphabet has to be 27.
- Barcode '{barcode}' has alphabetic characters.
- The entered barcode has a negative value. Try again.
- String lengths must match!
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/9fa41361875287b9.
Report an issue: GitHub.