简体   繁体   English

Python字符串替换子字符串(评估子字符串字典)

[英]Python String Replace SubString (Evaluate Substring dict)

Hi I need to make API calls to collect some data. 嗨,我需要进行API调用以收集一些数据。 The URL looks like this: 该URL如下所示:

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. 我尝试用不同产品的列表替换partnumber值,并且我正在考虑使用子字符串替换。

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

However, while I was trying to do that against the URL: 但是,当我尝试针对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 }}. 如果需要在文字文本中包含大括号字符,可以通过加倍{{和}}来转义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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