简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM