【问题标题】:In python, How can i add a $ symbol just before { in the api endpoint在 python 中,如何在 api 端点的 { 之前添加一个 $ 符号
【发布时间】:2019-07-05 03:46:56
【问题描述】:

我需要在每行的 { 之前添加一个 $ 符号。我怎样才能在python中做到这一点,

问题:使用 python 在传递这些 API 端点之前,我正在从 JSON 文件中读取所有 API 端点,我需要在左括号 {

之前附加一个 $ 符号

以下是从 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)

从上面的代码中,我需要进一步实现在打印之前在{旁边添加一个$符号。

下面的列表是我通过使用 python 读取 json 文件得到的:

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

预期是:

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

【问题讨论】:

  • newstring = oldstring.replace('{', '${')
  • 应该${ 变成${{ 吗?还是应该保留为${
  • .replace() 不会二次探底。
  • 应该是${。
  • 约翰·戈登,谢谢。现在我能够实现所需的输出。下面是 open("example.json", "r") 作为读取: data = json.load(reading) for path,data['paths'].items() 中的值: print(path.replace('{ '))

标签: python python-3.x append string-concatenation


【解决方案1】:

你可以使用.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}

【讨论】:

    【解决方案2】:

    您可以使用re 库。

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

    有关re 的更多信息,请浏览文档。 https://docs.python.org/3/library/re.html,这是一个非常有用的模块。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-15
      相关资源
      最近更新 更多