tags:

views:

77

answers:

4

i'm trying to do something pretty simple:

line = "name      :    bob"
k, v = line.lower().split(':')
k = k.strip()
v = v.strip()

is there a way to combine this into one line somehow? i found myself writing this over and over again when making parsers, and sometimes this involves way more than just two variables.

i know i can use regexp, but this is simple enough to not really have to require it...

A: 
":".join([k, v])
Matthew Flaschen
+1  A: 
import 're'
k,v = re.split(r'\s*:\s*', line)
line = ':'.join((k,v))
wilhelmtell
+7  A: 
k, v = [x.strip() for x in line.lower().split(':')]
oylenshpeegul
If performance is important I'd do the lower after the strip as you process less characters that way. k,v = [ x.strip().lower() for x in line.split(':') ]. But then again a compiled regular expression maybe faster yet.
Michael Anderson
@Michael, Premature optimisation is the root of all evil. We have no reason to think this code has any meaningful contribution to bad performance or that performance is an issue at all. I would guess that doing the lower after the strip (and therefore looking up and calling the method twice) would actually be *slower* for OP's sample, but I don't know or care and you don't know without timing it.
Mike Graham
+1  A: 
>>> map(str.strip,line.lower().split(":"))
['name', 'bob']
ghostdog74