Finding First or Last Item in a Python List

Posted by: scoopseven 12 years, 11 months ago

I had a small piece of code I was using to parse a search string in Python for Sphinx.  When you pass "verizon | mobile | at&t" to Sphinx (in boolean mode) it happily returns results.  However, if you pass "verizon | mobile | at&t | " it throws an "unexpected $end near ''" error.  So I needed to not add the extra pipe/or for the last element in my search string.  Using split() to turn the string into a list and then using the [-1] index, you're able to determine if you're on the last element and not add the extraneous "or."

wordlist = strip_stopwords(search['anywords']).split()
        for word in wordlist:
            searchstring += word
            if word != wordlist[-1]:
                searchstring += " | "

Currently unrated


Recent Tweets

Recent Posts

Archive

2013
2012
2011
2010
2009
2008
2007
2006

Categories

Authors

Feeds

RSS / Atom