[Tutor] Testing a string to see if it contains a substring (dw)

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Jan 23 11:37:56 CET 2015

On 22/01/2015 15:40, dw wrote:
> Thanks for your good comments.
> I do think I found a work around
> body = ""
> for x in range(0,len(line_array)):
>      test_line = len(re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',
>      line_array[x]))
>      if test_line > 0:
>          body = body + line_array[x]+"\n"

Using range in a Python for loop is often a code smell.  Your names are 
poor as well.  The Pythonic way is:-

body = ""
for line in line_array:
     linelen = len(re.findall(r'[0-9]{2}/[0-9]{2}/[0-9]{4}', line))
     if linelen > 0:
         body += line + "\n"

Also note that although the above is adequate for small data sets, the 
performance dives terribly as the size of the data set goes up.  Your 
homework for this weekend is to research how one normally joins strings 
in Python and report back.  Have a good one :)

My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

More information about the Tutor mailing list