slicing string
Gordon McMillan
gmcm at hypernet.com
Mon Jul 3 08:34:51 EDT 2000
Jarkko Veijalainen wrote:
>I'm real newbie with Python. I started learnig Python just last week. I
>have a problem slicing a string, imported from file. can anyone help me
>with simple solution. Input string follows this pattern:
>
> attr=value , attr2=value2, attr3= , attr4=value2.
>
>I have made an Object class, where all attributes are class variables.
>How can i slice that sring and store those att=value pairs in my object?
First part is easy:
import string
pairs = string.split(s, ',')
for pair in pairs:
tokens = string.split(pair, '=')
if len(tokens) == 2:
key = string.strip(tokens[0])
val = string.strip(tokens[1])
# see below
else:
# not sure what you want to do here
If I take you literally, then I would say:
Object.key = val
but I suspect you want a line at the top:
o = Object()
and then
o.key = val
- Gordon
More information about the Python-list
mailing list