delphi programming forums mysql charset mget recursive synonimos
free ventrilo servers hosting cs javascript delay python find in list
Back Forum New
abstract:

re.search(list, 'th')
But nothing happens when I run this in the Python shell.
I'm using Python  v2.5.4
Any ideas?
Thanks


Hi,
Im trying to search for a partial match within a list in Python.
For example
list = ['the', 'cat', 'bee']
Now I want to see if anything begins with 'th'
I've done some research and found some information on regular expression such as:
re.search(list, 'th')
But nothing happens when I run this in the Python shell.
I'm using Python  v2.5.4
Any ideas?
Thanks

TOP

First, the regular expression for finding "th" only at the beginning is "^th".
Your problem is, re functions only work on strings directly, not a list of strings.  So for example you could filter the list for the items that match:
Code:
  1. [string for string in list if re.match("^th", string)]
Copy Code

TOP

no need regex
Code:
  1. for item in mylist:
  2.     if item.startswith("th"):
  3.        print item
Copy Code

TOP

Hi,
Thanks for the help guys maybe someone could spot my mistake?
Why does this return false when it shouldn't
For example the letter 'h' returns false when theirs obviously words beginning with 'h' ?
The wordlist is here:
Link
Code :
Code:
  1. def can_word_be_made(word, wordlist):
  2.     for item in wordlist:
  3.         if item.startswith(word):
  4.             return True
  5.         else:
  6.             return False
Copy Code
Any ideas? Thanks !

TOP

abstract:

re.search(list, 'th')
But nothing happens when I run this in the Python shell.
I'm using Python  v2.5.4
Any ideas?
Thanks



Originally Posted by AKalair
Thanks for the help guys maybe someone could spot my mistake?
Why does this return false when it shouldn't
Well, it’s obvious: it returns right after checking the first item.

TOP


  For example the letter 'h' returns false when theirs obviously words beginning with 'h' ?
The words are all caps.  Convert both before testing.
Code:
  1. def can_word_be_made(word, wordlist):
  2.     word_caps = word.upper()
  3.     for item in wordlist:
  4.         if item.upper().startswith(word_caps):
  5.             return True
  6.         else:
  7.             return False
Copy Code




re.search(list, 'th')
But nothing happens when I run this in the Python shell.
I'm using Python  v2.5.4
Any ideas?
Thanks

TOP

Back Forum