AbtPst
AbtPst

Reputation: 8018

Python: How to remove quotes around numbers from string

I have a python string like this:

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

From the string, I want to remove the single quotes around the numbers that appear after value.

How can I write a regex that will detect only such numbers and replace the quotes around them?

Upvotes: 2

Views: 2097

Answers (1)

timgeb
timgeb

Reputation: 78700

Capture the number in a group, re-insert the group:

>>> 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'}"

Or, if this must be specific to the number after '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'}"

Upvotes: 7

Related Questions