TypeError for optional start parameter in string.find()
I'm having a bit of trouble understanding how this is happening. When I run the follo开发者_如何学Gowing:
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?
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. find
s 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.
精彩评论