String Splitter Brain Teaser

Ron_Adam radam2 at tampabay.rr.com
Mon Mar 28 04:27:30 CEST 2005


On Sun, 27 Mar 2005 14:39:06 -0800, James Stroud
<jstroud at mbi.ucla.edu> wrote:

>Hello,
>
>I have strings represented as a combination of an alphabet (AGCT) and a an 
>operator "/", that signifies degeneracy. I want to split these strings into 
>lists of lists, where the degeneracies are members of the same list and 
>non-degenerates are members of single item lists. An example will clarify 
>this:
>
>"ATT/GATA/G"
>
>gets split to
>
>[['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']]


Here's two ways without using regular expression.  Both about the
same.

s = list("ATT/GATA/G")
result = []
while len(s)>0:
    a = [s.pop(0)]
    if s[0] == '/':
        b = s.pop(0)
        a.append(s.pop(0))
    result.append(a)
print result

[['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']]    

                
s = "ATT/GATA/G"
result = []
while len(s)>0:
    if s[1:2] == '/':
        result.append([s[0],s[2]])
        s = s[3:]
    else:
        result.append([s[0]])
        s = s[1:]
print result

[['A'], ['T'], ['T', 'G'], ['A'], ['T'], ['A', 'G']]  




More information about the Python-list mailing list