代码之家  ›  专栏  ›  技术社区  ›  Hellbea

在python字符串中使用正则表达式替换某些字符

  •  -2
  • Hellbea  · 技术社区  · 7 年前

     id:'somecharet',  status: 'running', 
    

    如何使用正则表达式从 : id status "id" "status"

    需要的结果:

     "id":'somecharet',  "status": 'running',
    

    find = re.compile(r' (\S*?):')
    newstr = find.findall(new)
    

    我当然可以用 replace

    1 回复  |  直到 7 年前
        1
  •  0
  •   DonGru    7 年前

    为什么你会考虑使用正则表达式呢?IMHO the replace() 函数在这里就足够了。

    str = "id:'somecharet',  status: 'running', "
    print (str.replace('id', '"id"'))
    

    输出:

    "id":'somecharet',  status: 'running',