【问题标题】:string replacement of \1 (python) [duplicate]\1(python)的字符串替换[重复]
【发布时间】:2020-09-11 21:56:18
【问题描述】:

我想去掉下面字符串中[]里面的逗号:

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'

【问题讨论】:

  • 您需要仅使用正则表达式的解决方案还是任何解决方案都可以?
  • 传递一个可调用作为替换参数。 re.sub(reg_pattern, lambda x: x.group().replace(",",""), columns_data)

标签: python regex string replace substring


【解决方案1】:

试试这个:

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'

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-20
    相关资源
    最近更新 更多