0

For .find() how would you find the cases in multiple places?

For example:

string = 'banana'

string.find('na')

I want it to return [3, 5] by creating a blank list and appending it. How would I go about this?

Jason Sturges
  • 15,855
  • 14
  • 59
  • 80
user252017
  • 19
  • 4
  • Check out this question and answer: http://stackoverflow.com/questions/4664850/find-all-occurrences-of-a-substring-in-python – randwa1k Mar 02 '14 at 23:28

2 Answers2

1
>>> import re
>>> [m.start()+1 for m in re.finditer('na', 'banana')]
[3, 5]
anon582847382
  • 19,907
  • 5
  • 54
  • 57
0

Based on this answer, you can do:

>>> import re
>>> [m.start() for m in re.finditer('na', 'banana')]
[2, 4]

In most programming languages, you start counts with 0, not 1, that's why the "na"s start at 2 and 4, not 3 and 5.

Community
  • 1
  • 1
randwa1k
  • 1,502
  • 4
  • 19
  • 30