My line is:
line = "aaaaaaaaaaaaaaxxxxxxxxxxxxxxbbbbbbbbbbbbxxxxxxxxxxxxxxxxxxxbbbbbbbbbbb"
How can I find number of patches of "xxxxx" in line
? For example above the answer would be 2
.
Note that the number of 'x's
may vary.
My line is:
line = "aaaaaaaaaaaaaaxxxxxxxxxxxxxxbbbbbbbbbbbbxxxxxxxxxxxxxxxxxxxbbbbbbbbbbb"
How can I find number of patches of "xxxxx" in line
? For example above the answer would be 2
.
Note that the number of 'x's
may vary.
This is a good example of where regex can be quite useful. I'm not the world's best at regex, but here's a snippet that works:
import re
line = "aaaaaaaaaaaaaaxxxxxxxxxxxxxxbbbbbbbbbbbbxxxxxxxxxxxxxxxxxxxbbbbbbbbbbb"
patches = len(re.findall(r"(x+)", line))
This works by matching any group of 1 or more 'x' no matter how long.
You can use groupby
to group each "patch" and then count the number of occurances:
from itertools import groupby
line = 'aaaaaaaaaaaaaaxxxxxxxxxxxxxxbbbbbbbbbbbbxxxxxxxxxxxxxxxxxxxbbbbbbbbbbb'
number_of_x = sum(ch == 'x' for ch, _ in groupby(line))