简体   繁体   中英

How do I return string argument without brackets and quotes in Python

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()

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.

In Python, [] is shorthand for list() (Eg ['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() .

Eg

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 [#] (eg [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 index ing

In Terminal, you can test this out:

>>> groupid = ['asd']
>>> groupid
['asd']
>>> str(groupid)
"['asd']"
>>> str(groupid[0])
'asd'
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM