Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you do string interpolation with a URL that contains formatting characters?

Tags:

python

I'm trying to use URLLIB2 to open a URL and read back the contents into an array. The issue seems to be that you cannot use string interpolation in a URL that has formatting characters such as %20 for space, %3C for '<'. The URL in question has spaces and a bit of xml in it.

My code is pretty simple, looks something like this:

#Python script to fetch NS Client Policies using GUID

import sys
import urllib2

def GetPolicies(ns, guid):
    ns = sys.argv[1]
    guid = sys.argv[2]
    fetch = urllib2.urlopen('http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{%s}%22') % (ns, guid)

I've shortened the URL for brevity but you get the general idea, you get a 'Not enough arguments for format string' error since it assumes you're wanting to use the %3, %20, and other things as string interpolations. How do you get around this?

Edit: Solution requires Python 2.6+, 2.5 or prior has no support for the string.format() method

like image 950
Caley Woods Avatar asked Jan 30 '26 06:01

Caley Woods


1 Answers

You can double the % signs

url = 'http://%s/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%%3Crequest%%20configVersion=%%222%%22%%20guid=%%22{%s}%%22' % (ns, guid)

or you can use .format() method

url = 'http://{hostname}/Altiris/NS/Agent/GetClientPolicies.aspx?xml=%3Crequest%20configVersion=%222%22%20guid=%22{id}%%2''.format(hostname=ns, id=guid)
like image 182
nosklo Avatar answered Jan 31 '26 22:01

nosklo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!