简体   繁体   中英

Python String Replace SubString (Evaluate Substring dict)

Hi I need to make API calls to collect some data. The URL looks like this:

https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"myproduct","manufacturer":"my company"}]&fmt=json

I try to replace the partnumber value with a list of different products and I am thinking about using substring replacement.

>>> print "My name is {0}".format('/usr/bin')
My name is /usr/bin

However, while I was trying to do that against the URL:

>>> print 'https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"{0}","manufacturer":"my company"}]&fmt=json'.format('my product')
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
KeyError: '"partNumber"'

Somehow it is trying to evaluate the dictionary inside the string, which is totally beyond my knowledge why it is doing so.

Can anyone help me how to fix it?

You need to escape the other { and } using {{ and }} :

>>> print 'https://app.example.com/SearchService/search/xref?parts=[{{"partNumber":"{0}","manufacturer":"my company"}}]&fmt=json'.format('my product')
https://app.example.com/SearchService/search/xref?parts=[{"partNumber":"my product","manufacturer":"my company"}]&fmt=json

From docs :

If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}.

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