Comparing strings - akin to Perl's "=~"
Diez B. Roggisch
deets at nospam.web.de
Tue May 6 08:53:06 EDT 2008
krumblebunk at gmail.com wrote:
> Hello gurus,
>
> I am learning Python to take the place of Perl in my toolbox of bits
> and bobs, and writing something pretty simple in theory, but having a
> hard time in Python with it - I am using a 3rd party module, and I am
> sure the etiquette of this channel states that this is pure Python
> questions only, but please bare with me in light of this, as my
> question does indeed relate to Python only.
>
> I am grabbing the output from a SQL statement (using PyGreSQL 'pg'
> module), and when it returns the result, I am pulling it out as such:
>
> try:
> sc=pg.connect(dbname='mydb',host='dbhost',user='ppp')
> except pg.InternalError:
> print "Failed to execute SQL: %s" % sql
> exit
>
> for foo in sc.query(sql).dictresult(): <- this returns a dict of the
> result
> f=dict(foo)
> for k in f.iteritems()
> if k == '^Hostname': <-- need this sort of
> behaviour - match a partial string.
> print "%s" % f[3] <-- ..and if true, need to pull
> out the 4th column on that line.
>
> This breaks spectacularly -
>
> any ideas?
Use the module "re" to create regular expressions & out of these
mather-objects that will give you what you need.
The idiom is roughly translated to this:
m = re.search(r"^Hostname')
if m:
...
Diez
More information about the Python-list
mailing list