这实际上是一个比看起来更健壮的问题,因为它通常公开了一些对 web 开发有用的功能。您基本上是在问如何在字符串'http://www.myapp.com/finish_box?code=my_code&' 中分隔my_code。
好吧,让我们零零碎碎地接受它。首先,你知道你只需要问号后面的东西,对吧?我的意思是,你不需要知道你是从哪个网站得到它的(虽然这会很好保存,让我们保留它以防我们以后需要它),你只需要知道哪些参数被传回。让我们从 String.split() 开始:
>>> return_string = 'http://www.myapp.com/finish_box?code=my_code&'
>>> step1 = return_string.split('?')
["http://www.myapp.com/finish_box","code=my_code&"]
这将向 step1 返回一个包含两个元素的列表,"http://www.myapp.com/finish_box" 和 "code=my_code&"。好吧,地狱,我们在那里!让我们在等号上再次拆分第二个!
>>> step2 = step1[1].split("=")
["code","my_code&"]
看起来不错,我们快完成了!但是,这实际上并不允许对其进行任何更强大的使用。如果给我们呢:
>>> return_string = r'http://www.myapp.com/finish_box?code=my_code&junk_data=ohyestheresverymuch&my_birthday=nottoday&stackoverflow=usefulplaceforinfo'
我们的计划突然失效了。让我们打破& 符号上的第二组,因为这就是分隔键:值对的原因。
step2 = step1[1].split("&")
["code=my_code",
"junk_data=ohyestheresverymuch",
"my_birthday=nottoday",
"stackoverflow=usefulplaceforinfo"]
现在我们正在取得进展。让我们将它们保存为字典,好吗?
>>> list_those_args = []
>>> for each_item in step2:
>>> list_those_args[each_item.split("=")[0]] = each_item.split("=")[1]
现在我们在list_those_args 中有一个字典,其中包含 GET 传回给您的每个参数的键和值!科学!
那么你现在如何访问它?
>>> list_those_args['code']
my_code