1

If I have:

127.0.0.1 - - [24/Feb/2014:03:36:46 +0100] "POST /info HTTP/1.1" 302 0 "http://website.com" "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36" "name=josh&zipcode=12345"

How would I be able to extract "josh" and "12345" to their own variables?

3 Answers 3

4

Split the string by spaces, take the last element, strip quotes and use urlparse.parse_qsl() to parse query parameters:

>>> from urlparse import parse_qsl
>>> s = '127.0.0.1 - - [24/Feb/2014:03:36:46 +0100] "POST /info HTTP/1.1" 302 0 "http://website.com" "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36" "name=josh&zipcode=12345"'
>>> params = parse_qsl(s.split()[-1].strip('"'))
>>> params
[('name', 'josh'), ('zipcode', '12345')]

Then, to assign variables to the parameter values, you can unzip params:

>>> name, zipcode = zip(*params)[1]
>>> name
'josh'
>>> zipcode
'12345'
Sign up to request clarification or add additional context in comments.

Comments

3

You can use this following code, assuming all of the following strings will be in the same format:

>>> info = '127.0.0.1 - - [24/Feb/2014:03:36:46 +0100] "POST /info HTTP/1.1" 302 0 "http://website.com" "Mozilla/5.0 (Windows NT 6.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.76 Safari/537.36" "name=josh&zipcode=12345"'
>>> name = info.split()[-1].split('&')[0].split('=')[1]
>>> code = info.split()[-1].split('&')[1].split('=')[1]
>>> name
'josh'
>>> code
'12345'

The first .split() is to get the entire string as a list.

The [-1] is to get the last item in the list.

The .split('&') is to split the last sequence by the '&'.

The [0] or [1] is to specify which value we want to obtain, the name or the code.

The split('=') is to split each value by the equals sign, so that we can obtain the name or the code as one value.

The last [1] is to get the last value, basically to exclude the 'name' or 'zipcode'.

Comments

1

You could use the split function...

o = "name=josh&zipcode=12345"

a = o.split('&') # ['name=josh', 'zip=12345']
d = dict(s.split('=') for s in a)

would give you a nice dictionary of key value pairs :)

{'name':'josh','zip':12345}

or you could use something else depending on what you need... http://docs.python.org/2/library/string.html

string.find(s, sub[, start[, end]])
    Return the lowest index in s where the substring sub is found such that sub is wholly contained in s[start:end]. Return -1 on failure. Defaults for start and end and interpretation of negative values is the same as for slices.

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.