简体   繁体   English

在python中,如何在api端点中的{之前添加$符号

[英]In python, How can i add a $ symbol just before { in the api endpoint

I need to add a $ symbol before the { on each line.我需要在每行的 { 之前添加一个 $ 符号。 how can I do it in python,我怎么能在python中做到这一点,

Problem: Using python I am reading all the API endpoint from the JSON file before I pass those API endpoints, I need to append a $ symbol just before to the open parenthesis {问题:在传递这些 API 端点之前,我正在使用 python 从 JSON 文件中读取所有 API 端点,我需要在左括号之前附加一个 $ 符号 {

Below is the code reads the API endpoint name from JSON file and prints.下面是从 JSON 文件中读取 API 端点名称并打印的代码。

import json
with open("example.json", "r") as reads: # Reading all the API endpoints  from json file.
    data = json.load(reads)
    print(data['paths'].items())
    for parameters, values in data['paths'].items():
        print(parameters)

From the above code, I need to go further to achieve adding a $ symbol next to { before printing it.从上面的代码来看,我需要进一步实现在打印之前在 { 旁边添加 $ 符号。

Below list i get by reading the json file using python:下面是我通过使用 python 读取 json 文件得到的列表:

/API/{id}/one
/{two}/one/three
/three/four/{five}

Expected is:预期是:

/API/${id}/one
/${two}/one/three
/three/four/${five}

You Can use re library.您可以使用re库。

for parameters, values in data['paths'].items():
     print(re.sub('{', '${', parameters))

For more info on re , Go through the doc.有关re更多信息,请阅读文档。 https://docs.python.org/3/library/re.html , It's a very helpful module. https://docs.python.org/3/library/re.html ,这是一个非常有用的模块。

You could use .replace() .你可以使用.replace()

>>> obj="""
... /API/{id}/one
... /{two}/one/three
... /three/four/{five}
... """
>>> newobj = obj.replace('{','${')
>>> print(newobj)

/API/${id}/one
/${two}/one/three
/three/four/${five}

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

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