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
  • 15,057
  • 4
  • 35
  • 65
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,583
  • 1
  • 18
  • 41
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
  • 10,365
  • 5
  • 46
  • 73