英文:
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)]}}"
我尝试使用ast
,eval
和json.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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论