1

I have a URL like the following -

url = "http://servername:8080/api/environment/component.get?query=(name LIKE '%componentname%')"

I want to replace the following values with argument parameters I have as strings -

servername
environment
component
componentname

I want it then to be passed into requests -

r = requests.get(url, auth=('domain\user', 'password')

The problem is I can't figure out how to replace the values. I can't do %s, %d because it's possible that the value in %componentname% could start with an s or d which would break the encode.

3
  • 2
    Use string.format with { } to escape. You can even use {0} {1} etc to avoid accidental escaping Commented Aug 17, 2015 at 18:01
  • I actually did <servername> and then did url.replace('<servername>', 'server') seems inefficient though to have to have 4 separate url.replace... Commented Aug 17, 2015 at 18:05
  • You may want to look into the uritemplate package. Commented Aug 19, 2015 at 11:50

2 Answers 2

2

From what I understand the following solution should work for you, and it's more straight forward(It was also sugested in the first comment by user Tim Castelijns):

url = "http://{0}:8080/api/{1}/{2}.get?query=(name LIKE '%{3}%')".format(servername, environment, component, componentname)

If you want more readability you could even do it like this:

url = "http://{servername}:8080/api/{environment}/{component}.get?query=(name LIKE '%{componentname}%')".format(servername, environment, component, componentname)
Sign up to request clarification or add additional context in comments.

1 Comment

The second option does not work for me (using python 3.9), actually what works is "http://{servername}:8080/api/{environment}/{component}.get?query=(name LIKE '%{componentname}%')".format(servername=servername, environment=environment, component=component, componentname=componentname)
0

You can use python's inbuilt string concatenation.

url = "http://servername:8080/api/environment/component.get?query=(name LIKE '"+ componentname +"')"

It will append number or string as it is and you don't need to take care of %s or %d.

3 Comments

I tried this with all the replacements and it didn't like it because of the internal '' and the outside ""
Can you pls clarify. You can always escape internal quotes.
@whoisearth just use ' and " then. They mix well in python. Example 'this is "a string" that is valid'

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.