2

From '123456789' I want to find all (overlapping) matches of 3 consecutive numbers:

ListIWant = [123,234,345,456,567,678,789]

I tried:

print(re.compile(r"(\d){3}").findall('123456789'))

Output I currently get:

['3', '6', '9']

And also I want to know if there is something more efficient to count the number of matches instead of using len(ListIWant)

I'm learning English also, It will be grateful if you correct or suggest me better words/ways to express myself in this place.

smci
  • 32,567
  • 20
  • 113
  • 146
Marce
  • 21
  • 2
  • 1
    **Solution:** `re.findall(r'(?=(\d{3}))', a)` gives `['123', '234', '345', '456', '567', '678', '789']` – smci Jul 18 '21 at 05:47

2 Answers2

2

Use a comprehension to build your list:

s = '123456789'
w = 3  # window size
l = [int(s[i:i+3]) for i in range(len(s) - w + 1)]
>>> l
[123, 234, 345, 456, 567, 678, 789]
Corralien
  • 109,409
  • 8
  • 28
  • 52
1
a= '123456789'
ListIWant = []
for i, ele in enumerate(a):
    if i < len(a)-3:
        if (int(a[i+1]) == int(ele)+1) and (int(a[i+2]) == int(ele) + 2):
            ListIWant.append(int(ele+a[i+1]+a[i+2]))

    else:
        if (int(a[i+1]) == int(ele)+1) and (int(a[i+2]) == int(ele) + 2):
            ListIWant.append(int(ele+a[i+1]+a[i+2]))
        break

Output:

[123, 234, 345, 456, 567, 678, 789]
Prakash Dahal
  • 4,388
  • 2
  • 11
  • 25