1

This may be worded incorrectly because I'm a wee beginner, but if I have a string how to I find a certain characters index like you can with the .index thing in lists.

With a list it makes sense:

 l = ["cat", "dog", "mouse"]

 animal = l.index["dog"] 

will return [1], but how do I do the same thing with strings . . .

 s = "mouse"

 animal_letter = s.index["s"]

it says there is no attribute .index

Is there another way I can do this?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
codeman99
  • 87
  • 2
  • 2
  • 6
  • 1
    `animal_letter = s.index("s")` don't used brackets. `l.index["dog"]` does not work either. – dansalmo Nov 10 '13 at 19:54
  • Can't find a definitive answer to this, is there a difference between my method and yours? s.find vs s.index? – Will P Nov 11 '13 at 22:34

1 Answers1

4

Try the string.find method.

s = "mouse"
animal_letter = s.find('s')
print animal_letter

It returns the 0-based index (0 is the first character of the string) or -1 if the pattern is not found.

>>> "hello".find('h')
0
>>> "hello".find('o')
4
>>> "hello".find("darkside")
-1
kfsone
  • 23,617
  • 2
  • 42
  • 74
Will P
  • 192
  • 1
  • 9