string - Python - Why is this function not returning the index for white space? -


this code return index of numbers , and non-alphanumeric characters. however, return index first white space not of others , i'm not sure why.

shoestring = "fwefw1234132 lkjaldskf98:[]['asd fads fadsf"  n in shoestring:     if n.isalpha():         continue     else:         print n, shoestring.index(n) 

each time, you're calling shoestring.index(n). n ' ' character. has no way of knowing whether want first space, or second, or 43rd, returns first space.

the right way keep track of index, instead of searching find it.* enumerate function makes easy:

for i, n in enumerate(shoestring):     if n.isalpha():         continue     else:         print n, 

as side note, can make code lot simpler reversing if, don't need continue:

for i, n in enumerate(shoestring):     if not n.isalpha():         print n, 

you can have more fun using filter function or comprehension:

nonalphas = ((n, i) i, n in enumerate(shoestring) if not n.isalpha()) print '\n'.join('{} {}'.format(n, i) n, in nonalphas) 

* if got search right, make code lot slower. if have million-character string of spaces, each search has check million characters, , have once each space, means 1 trillion comparisons. if keep track of index go, it's 1 million comparisons. in technical terms, it's linear instead of quadratic.


Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -