0

I'm very new to Python and so am struggling with what is probably very simply to a seasoned Python programmer.

The problem below is that when the groupid argument is supplied with a value, it is evaluated to ['groupid'].

Can someone please explain how I concatenate the string so that it simply has the groupid value without the square brackets and singles quotes?

Many thanks,

import sys
import xbmcgui
import xbmcplugin
import urllib
import urlparse

import xbmc, xbmcaddon, xbmcvfs, simplejson, urllib2

base_url = sys.argv[0]
addon_handle = int(sys.argv[1])
args = urlparse.parse_qs(sys.argv[2][1:])

xbmcplugin.setContent(addon_handle, 'movies')

def build_url(query):
    return base_url + '?' + urllib.urlencode(query)

mode = args.get('mode', None)
groupid = args.get('groupid', None)

if (groupid is None): 
    testurl = 'hxxp://webserver.com/json.php'
else:
    testurl = 'hxxp://webserver.com/json.php?group=' + str(groupid)

req = urllib2.urlopen(testurl)
response = req.read()
req.close()
Graeme Cowie
  • 17
  • 1
  • 5

2 Answers2

2

urlparse.parse_qs always returns a dictionary of lists, since a parameter name could be repeated in the query string and returning a list will allow you to see multiple values of the parameter. Since you presumably expect only one value for your query parameter of "groupid", you just want the first element of the list, hence:

groupid[0]

instead of

str(groupid)

str(groupid) was printing a string represention of the list.

Geoff Genz
  • 2,006
  • 17
  • 20
0

In Python, [] is shorthand for list() (E.g. ['groupid_1', 'groupid_2', 3, 4])

So in your code: groupid = args.get('groupid' or None) the .get('groupid', ... seems to return a dict() (as .get is used on dicts), but returns a list().

E.g.

args = {
    'groupid': [1, 14, 23]
    ...
}

So: groupid = args.get('groupid')

makes

groupid = [1, 14, 23]

So calling str(groupid) returns "[1, 14, 23]"

Whereas calling str(groupid[1]) returns 14

ANSWER Change your str(groupid) to str(groupid[0]).

Using [#] (e.g. [0]), is saying, return the first item in the list, whereas [1], says return the second item in the list. [#]'s in programming is called indexing

In Terminal, you can test this out:

>>> groupid = ['asd']
>>> groupid
['asd']
>>> str(groupid)
"['asd']"
>>> str(groupid[0])
'asd'
>>> 
Douglas Denhartog
  • 2,036
  • 1
  • 16
  • 23