0

I'm having a bit of trouble understanding how this is happening. When I run the following:

def find_in_string(string, ch):
    count = 0
    index = 0
    while 0 <= index < len(string):
        if string.find(string, ch, index) != -1:
            return True

find_in_string('asdfasdf', 's')

Here's what is I get:

TypeError: slice indices must be integers or None or have an __index__ method

However, running this through the interpreter like so:

index = 0
if string.find('asdfasdf', 's', index) != -1:
    return True

It returns 'True'. So I'm not understanding how string.find isn't getting passed an integer for the starting index in the above function. Any advice appreciated!

EDIT: For whatever reason, the above function now works after importing string again. Perhaps too much coffee?

2
  • Here's some advice: Don't use string as a variable name. It's a commonly used module that comes with python. Commented Sep 15, 2011 at 21:01
  • Thanks for the tip. I thought that might have something to do with it so i fixed that. Commented Sep 15, 2011 at 21:05

1 Answer 1

1

Your misunderstanding seems to come from importing the string module as well as naming your variable string.

You don't need to import the module to use find, and you could name your variable something else if you do need to import the module to do something else.

The type is str not string.

find doesn't work like that. You mean

string.find(ch) # ', index' if you want

if your variable is named string or

str.find(string, ch) # ', index' if you want

if your variable is named string and you really want to access it on the class / type str (no reason to).

You call find on the string you're searching in, you don't pass the string to find manually unless you're accessing find on the class / type. finds first manually passed argument is the string to search for, followed by start and end indexes. Since you appear to be searching the whole string, they can be omitted.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a heap! I'm not really sure why I thought calling find in this way was a good idea. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.