0

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.

Ma0
  • 14,712
  • 2
  • 33
  • 62
ana
  • 19
  • 2

2 Answers2

3

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.

bendl
  • 1,504
  • 1
  • 19
  • 38
1

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))
Jonas Adler
  • 9,571
  • 3
  • 41
  • 73