3

I have following string

adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0

I need only the value of adId,siteId and userId. means

4028cb901dd9720a011e1160afbc01a3

8a8ee4f720e6beb70120e6d8e08b0002

5082a05c-015e-4266-9874-5dc6262da3e0

all the 3 in different variable or in a array so that i can use all three

4 Answers 4

18

You can split them to a dictionary if you don't need any fancy parsing:

In [2]: dict(kvpair.split(':') for kvpair in s.split(';'))
Out[2]:
{'adId': '4028cb901dd9720a011e1160afbc01a3',
 'siteId': '8a8ee4f720e6beb70120e6d8e08b0002',
 'userId': '5082a05c-015e-4266-9874-5dc6262da3e0'}
Sign up to request clarification or add additional context in comments.

1 Comment

It's a copy paste from ipython interactive shell.
1

You could do something like this:

input='adId:4028cb901dd9720a011e1160afbc01a3;siteId:8a8ee4f720e6beb70120e6d8e08b0002;userId:5082a05c-015e-4266-9874-5dc6262da3e0'

result={}
for pair in input.split(';'):
    (key,value) = pair.split(':')
    result[key] = value

print result['adId']
print result['siteId']
print result['userId']

Comments

1
matches = re.findall("([a-z0-9A-Z_]+):([a-zA-Z0-9\-]+);", buf)

for m in matches:
    #m[1] is adid and things
    #m[2] is the long string.

You can also limit the lengths using {32} like

([a-zA-Z0-9]+){32};

Regular expressions allow you to validate the string and split it into component parts.

Comments

0

There is an awesome method called split() for python that will work nicely for you. I would suggest using it twice, once for ';' then again for each one of those using ':'.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.