【问题标题】:I would like to slice a string bounded between ${ and }我想切片 ${ 和 } 之间的字符串
【发布时间】:2019-11-26 23:08:09
【问题描述】:

我想提取${ 和} 之间的字符串。

例子:

/one/${two}
/${three}/one/${four}
/five/${six}/seven

我有代码,它从 json 字符串中读取内容,除了 API 端点之外什么都没有。在此过程中,我想提取${ 和} 之间的单词或字符串并将它们存储在一个变量中。

下面是从 json 文件中读取数据内容的相同代码,

with open("example.json", "r") as reading:
    data = json.load(reading)
    for path, values in data['paths'].items():
        print(path.replace('{', '${'))  # If required used print statement
        for value in values:
            print(value)

输出:

two
three
four
six

【问题讨论】:

  • 为什么不使用正则表达式捕获组?

标签: python python-3.x string slice


【解决方案1】:

我们可以在这里尝试使用re.findall,模式为\$\{(.*?)\}:

input = "/${three}/one/${four}"
matches = re.findall(r'\$\{(.*?)\}', input)
print(matches)

打印出来:

['three', 'four']

【讨论】:

  • 谢谢蒂姆。我想了解,有没有办法可以将输出“三”和“四”拆分为两个不同的变量。同样,我有一个案例是我可能有“五”、“六”和“四”,我想保存到一个单独的变量中,因为我需要将这些输出写入 CSV 文件的列中。
  • @ArunPrasath 我的答案的输出已经是一个列表。您可以迭代列表并将这些值分配给您想到的任何局部变量。
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2013-10-22
  • 1970-01-01
相关资源
最近更新 更多