Python - Why is this function not returning the in

2019-06-05 22:05发布

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)

2条回答
疯言疯语
2楼-- · 2019-06-05 22:28

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.

查看更多
闹够了就滚
3楼-- · 2019-06-05 22:49

Each time, you're calling shoestring.index(n). That n 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:

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

As a side note, you can make your code a lot simpler by just reversing the if, so you don't need the continue:

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

You can have even more fun using the filter function or a comprehension:

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

* 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.

查看更多
登录 后发表回答