1

How can I write a function that returns the index of a single character in a string without using the index method a.k.a string.index('some random character')?

5
  • Why can't you use that method? Commented Apr 2, 2011 at 0:23
  • en.wikipedia.org/wiki/String_searching_algorithm Commented Apr 2, 2011 at 0:25
  • jhocking -- its specified in the instructions of my hw set not use that method Mr E -- thank you for the link, unfortunately its all greek to me =/ Commented Apr 2, 2011 at 0:29
  • Thank you everybody, the answers you all gave are all valid Once again, Thank you very much! Commented Apr 2, 2011 at 0:36
  • Mr E gave you the link because you wrote "function that returns the index of a string" whereas you meant "function that returns the index of a char". The first is a much more comple problem. Commented Apr 2, 2011 at 1:01

3 Answers 3

3

Another variant that works with multiple occurrences of char in string.

def idx(string, char):
  for key, x in enumerate(string):
    if x == char:
      print key
Sign up to request clarification or add additional context in comments.

Comments

0

it's a school task?

def ind(the_string, the_char):
   i = 0
   for a_char in the_string:
       if a_char == the_char: return i
       i += 1
   return -1

2 Comments

yes its for a hw set, and thank you very much Cek this did the trick!
the enumerate from lecodesportif's answer saves you the two lines of code, and it's nice for i, a_char in enumerate(the_string)
0

index() is the same thing as find() except for the error when the string isn't found.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.