Keeping only certain characters in a string using Python?

A very elegant and fast way is to use regular expressions:

import re

str="ag ct oso gcota"
str = re.sub('[^atcg]', '', str)

"""str is now 'agctgcta"""

Leave a Comment