Day 39 - Simple Regular Expression

The last few days have been tough. I’ve felt bad about not blogging my progress, though the time seems to get away from me, and I just don’t set aside 5-10min to sit down and do it. sigh I’ve got to do better at this. I honestly don’t mind if people aren’t reading it, it’s just the promise of taking the necessary action to do it, and not fulfilling that promise that gets to me. Anyway, I’m SLOWLY chomping down this Python Next Level course, and it’s been marginally interesting to go though. This section that I’m on now seems long and drawn out, but here and there are snippets of interesting concepts that I’ve tried to commit to memory. Perhaps I’m not internalizing it because it’s just not enough of a habit for me yet. Hopefully, with this week’s brand new schedule, things will get better. More on the recent change in an upcoming post…for now, here’s a very brief example of using a simple regular expression from the course:

#!/usr/bin/env python
""" re_search.py - searches a string for a leading zero."""
import re

def noFirstZero(formula):
    """ uses a regular expression search to look for a leading zero. """
    return not re.search(r'\b0[0-9]', formula)

def test_noFirstZero(L):
    """ runs a quick test. """
    for formula in L:
        print formula, noFirstZero(formula)

""" Test """
L = ['123', '406', '023', '543 0543', '087 65', '00', '432 123']
test_noFirstZero(L)

Here in this example, we’re looking for numbers that do not begin with zero. The ‘magic’ is in the use of the re python library. The noFirstZero method uses it to determine if a string of numbers leads out with a zero at any point in the string. If it does, it will return the appropriate result. This method will be used in the upcoming solution to the ‘secret decoder’ problem we’ve been working on in the section.

More stuff soon….

Jason T Clark

Jason T Clark

Father. Musician. Gamer. Coder.

comments powered by Disqus
rss facebook twitter github youtube mail spotify instagram linkedin