Picking apart strings

Russ P. Russ.Paielli at gmail.com
Wed Jun 4 01:21:12 CEST 2008


On Jun 3, 11:44 am, tmallen <thomasmal... at gmail.com> wrote:
> Is there a way to pick apart this text without resorting to regular
> expressions?
>
> p {
>     color: black;
>
> }
>
> p -> element
> color -> property
> black -> value

Sure.

data = txt.strip("}").split("{")

element = data[0].strip()

items = data[1].split(";")

for item in items:

    data = item.split(":")
    property = data[0].strip() # avoid this keyword
    value = data[1].strip()

I didn't test this. Also, the module suggested in the other reply
might make more sense, depending on how much of this sort of thing you
need to do.



More information about the Python-list mailing list