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

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Jan 22 08:09:50 CET 2015


On 21/01/2015 18:14, dw wrote:
> Hello Python Friends.
> I have a string array, called "line_array".
>
> There may be up to 50 or more elements in the array.
> So:
> - line_array[1] may contain "01/04/2013  10:43 AM        17,410,217
> DEV-ALL-01-04-13.rlc\n"
> - line_array[2] may contain "01/25/2013  03:21 PM        17,431,230
> DEV-ALL-01-25-2013.rlc\n"
> - line_array[3] may contain "\n"
>
> I want to retain all elements which are valid (i.e. contains a date
> value xx/xx/xxxx)
> So I'm using a regex search for the date value located at the start of
> each element...this way
>
> misc_int1 =
> re.search(r'[0-9]{2}/[0-9]{2}/[0-9]{4}',line_array[x]).start()
>
> This method works really well when the regex date characters are found.
> It returns the value 0 to misc_int1 because the date regex starts at 0
> position.
> I was hoping the .start() method would return a -1 value for the
> instance in which the regex search string is not found.
> That way I could iterate through the elements and retain only the valid
> ones.
>
> However, the .start() method throws an error if the regex search string
> is not found.
>
> Your suggestions greatly appreciated!
> Thanks!!
> d :-]
>

I'd use 
https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime 
to test the first ten characters of the string.  I'll leave that and 
handling IndexError or ValueError to you :)

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