This code will return the index of the numbers and and the non-alphanumeric characters. However, it will only return the index for the first white space but not any of the others and I'm not really sure why.
shoestring = "fwefw1234132 lkjaldskf98:[]['asd fads fadsf"
for n in shoestring:
if n.isalpha():
continue
else:
print n, shoestring.index(n)
The string index() method returns the index of the first match. You are asking it for the first substring that matches
' '
, and that's what it gives.Each time, you're calling
shoestring.index(n)
. Thatn
is just a' '
character. It has no way of knowing whether you want the first space, or the second, or the 43rd, so it just returns you the first space.The right way to do this is to keep track of the index, instead of searching to find it.* The
enumerate
function makes this very easy:As a side note, you can make your code a lot simpler by just reversing the
if
, so you don't need thecontinue
:You can have even more fun using the
filter
function or a comprehension:* Even if you got the search right, it would also make your code a lot slower. If you have a million-character string of all spaces, each search has to check a million characters, and you have to do this once for each space, which means one trillion comparisons. If you just keep track of the index as you go, it's only one million comparisons. In technical terms, it's linear instead of quadratic.