Issue
I'm stuck with regular expressions in Python...
#!/usr/bin/python3
import re
combi="ABBAEAADCA"
one_a = len(re.findall('[^A](A)[^A]', combi))
print("A:"+str(one_a))
I try to make this variable (one_a) contain the number of A's that appear alone (3) but it does not count those at the beginning and end of lines so....
one_a = len(re.findall('\A(A)[^A]', combi))
print("A ini:"+str(one_a))
one_a += len(re.findall('[^A](A)[^A]', combi))
print("A_cen:"+str(one_a))
one_a += len(re.findall('[^A](A)\Z', combi))
print("A_end:"+str(one_a))
but it didn't work either when in this particular case the value that should stay in the variable should be 3. I would appreciate knowing what I am missing or what mistake I am making. Thank you very much
Solution
You can combine start-of-string (^
) and end of string ($
) with regular character classes through the or (|
) operator.
re.findall(r'(?:^|[^A])A(?:$|[^A])', combi)
This gives you all substrings where A
is either surrended by start of string and end of string, start of string and not-A, not-A or end of string or not-A and not-A.
>>> re.findall(r'(?:^|[^A])A(?:$|[^A])', combi)
['AB', 'BAE', 'CA']
Applying len
to this list gives you the count of single A's.
Answered By - MatsLindh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.