0

I want my python 2.7 program to get the index of specific characters in a string. So like this:

Get the index of the [ and ] brackets in any string. For example:

"Hello World [These brackets] Hello World"

The program should return 12 and 27. Is there any way to make my python program to do this? If not, then I'm out of luck.

Supercolbat
  • 311
  • 2
  • 8
  • 18

3 Answers3

3

The indexof function in python is index:

>>> "Hello World [These brackets] Hello World".index('[')
12

>>> "Hello World [These brackets] Hello World".index(']')
27
JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
1

What about index?

text = "Hello World [These brackets] Hello World"
idx1 = text.index("[")?
idx2 = text.index("]")?

Warning, this returns only the first match.

JuniorCompressor
  • 19,631
  • 4
  • 30
  • 57
Christian Sauer
  • 10,351
  • 10
  • 53
  • 85
1

One naive approach which you can see but still I prefer to use indexof function:

>>> a = "Hello World [These brackets] Hello World"
>>> for i in xrange(len(a)):
...     if a[i] == '[' or a[i] == ']':
...             print i
... 
12
27
Shashank
  • 1,105
  • 1
  • 22
  • 35
  • Can I change xrange to range, or is xrange there for a reason? – Supercolbat Feb 28 '17 at 22:24
  • Sometimes it's better to use xrange over range but still you can use range there is no problem in that. Try to read this: http://stackoverflow.com/questions/94935/what-is-the-difference-between-range-and-xrange-functions-in-python-2-x – Shashank Mar 01 '17 at 03:36