fettig.net

I did not know that

Posted by Abe on Tuesday, November 26, 2002 @ 6:01 pm

Here’s a fairly common programming task:  Given a string, see if it begins with another string.  For example, you may have a list of words, and you want to grab only the ones that begin with "Test".  So you may do something like this (for those who just walked in, we’re talking Python here):

for word in wordList:

    if word[:4] == "Test":

print word

…which is really not too bad, except that you’ve hard coded your test as being the first four characters, so later if you change "Test" to something else you have to change the [:4] bit to match.  So instead you might do this:

searchWord = "Testing"

for word in wordList:

    if word[:(len(searchWord)] == searchWord:

print word

Which is a bit more flexible, but harder to read.  Still, that’s what I had been doing most of the time.  But it turns out that Python gives you a much better way, that I’d never seen before just now:

for word in wordList:

    if word.startswith("Test"):

        print word

Yes, every Python string has a startswith method, that works just the way you’d expect it to.  Thanks to Mark for indirectly pointing this out to me through his code.

No Comments

No comments yet.

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.