在Python中给字典字符串加单引号。

huangapple go评论49阅读模式
英文:

Add single quotes to dict string python

问题

以下是我有的一个字典字符串:

s = "{0: {name: [(.1, 0), (.2, 0), (.3, 0)], address: [(get--some\data, 0), (2, 0), (3, 0)]}}"

我尝试使用astevaljson.loads()将上述字典字符串转换为字典类型,但由于字典缺少引号,所以存在一些问题。

是否有人能帮助我将单引号添加到所有键和值,如下所示:

s = "{'0': {'name': [('.1', '0'), ('.2', '0'), ('.3', '0')], 'address': [('get--some\\data', '0'), ('2', '0'), ('3', '0')]}}"

我尝试使用正则表达式添加引号,但这个字符串不会有静态值,例如,元组值的列表在请求之间可能会有不同的大小。

这是我尝试过的代码:

a = re.sub(r'((\w+)|(\w+\s*?\w+)):', r"'\\1':", s)

上面的正则表达式可以帮助我为键添加引号,但我需要帮助将引号添加到值中。

英文:

Below is a dict string I have:

s= "{0: {name: [(.1, 0), (.2, 0), (.3, 0)], address: [(get--some\data, 0), (2, 0), (3, 0)]}}"

I tried converting the above dict string to dict type by using ast, eval, and json.loads(). Due to the dict's lack of quotes, there are some issues with that.

Would someone be able to help me add single quotes to all of the keys and values as follows:

s= "{'0': {'name': [('.1', '0'), ('.2', '0'), ('.3', '0')], 'address': [('get --some\data', '0'), ('2', '0'), ('3', '0')]}}"

I tried adding quotes using regex, but this string won't have static values, like a list of tuple values can vary in size between requests.

Here is the code I tried:

a = re.sub(r'((\w+)|(\w+\s*?\w+)):', r"'':", s)

above regex is helping me add quotes to keys. i would need help on adding quotes to values as well

答案1

得分: 0

  • 正则表达式
(?!\s)([^][{}():,]+?)(?=\s*[,\):\]}])
  • 替换
''
  • Python 代码
a = re.sub(r'(?!\s)([^][{}():,]+?)(?=\s*[,\):\]}])', r"''", s)
  • 您可以在此处检查测试案例(https://regex101.com/r/vnbphk/1)
英文:

You may try this, it could satisfy most of your cases:

  • regex
(?!\s)([^][{}():,]+?)(?=\s*[,\):\]}])
  • substitution
''
  • Python code
a = re.sub(r'(?!\s)([^][{}():,]+?)(?=\s*[,\):\]}])', r"''", s)

You can check the test cases here

huangapple
  • 本文由 发表于 2023年2月10日 12:34:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/75406983.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定