Python:如何从字符串中删除数字周围的引号

时间:2016-03-30 17:50:24

标签: python regex string python-3.x

我有一个像这样的python字符串:

"""
{id: 'id_0_4', value: '8450223051', name: 'XAD3', parent: 'id_0'},
{id: 'id_0_5', value: '509071269', name: 'ABSD', parent: 'id_0'}
"""

从字符串中,我想删除value之后显示的数字周围的单引号。

如何编写只检测此类数字并替换它们周围引号的正则表达式?

1 个答案:

答案 0 :(得分:5)

捕获组中的数字,重新插入组:

>>> import re
>>> s = """{id: 'id_0_4', value: '8450223051', name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: '509071269', name: 'ABSD', parent: 'id_0'}"""
>>> re.sub("'(\d+)'", r'\1', s)
"{id: 'id_0_4', value: 8450223051, name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: 509071269, name: 'ABSD', parent: 'id_0'}"

或者,如果这必须特定于'value'之后的数字:

>>> re.sub("(value:\s*)'(\d+)'", r'\1\2', s)
"{id: 'id_0_4', value: 8450223051, name: 'XAD3', parent: 'id_0'}, {id: 'id_0_5', value: 509071269, name: 'ABSD', parent: 'id_0'}"