首页 > 解决方案 > \1 (python) 的字符串替换

问题描述

我想删除下面字符串中 [] 内的逗号:

columns_data = '6, 7, 1729, 7, 7, [5, 6, 4, 6], [66, 55] ,45, 23' 我希望它是 '6, 7, 1729, 7, 7, [ 5 6 4 6], [66 55] ,45, 23'

我做了以下,但它不起作用......

re.sub('([[^[]*])', str(r'\1').replace(","," ") , columns_data ) '6, 7, 1729, 7, 7, [5 , 6, 4, 6], [66, 55] ,45, 23'

标签: pythonregexstringreplacesubstring

解决方案


尝试这个:

import re  
text =  '6, 7, 1729, 7, 7, [5, 6, 4, 6], [66, 55] ,45, 23'  
re.sub(r'(\[.*?\])', lambda x: x.group().replace(',', ''), text)

输出:

'6, 7, 1729, 7, 7, [5 6 4 6], [66 55] ,45, 23'

推荐阅读