【问题标题】:How can I remove spaces within parentheses in a string? [duplicate]如何删除字符串中括号内的空格? [复制]
【发布时间】:2020-01-29 15:28:09
【问题描述】:

这是我的字符串

191, 4296092, datetime.date(2015, 11, 12), '2017-10-17 14:20:50.0', '&V101OLDOC'

我想删除括号内的空格。

示例:- re.sub(r'\([\s+]\)'

【问题讨论】:

  • 要轻松删除空格,请使用string.replace() 函数:>>> {your_string}.replace(" ", "")
  • OP 只想删除“带括号”的空格。
  • @JohnnyMopp 正确,这就是他们想要的——但为什么呢?根据 PEP,这些空间非常好......
  • 这个命令有效:re.sub(r'(.*?)', lambda x: ''.join(x.group(0).split()), str(gp_row_list) )我在这个链接中找到了它stackoverflow.com/questions/34088489/…谢谢大家的回复

标签: python python-3.x


【解决方案1】:

尝试以下方法:

string = "191, 4296092, datetime.date(2015, 11, 12), '2017-10-17 14:20:50.0', '&V101OLDOC'"
string.split('(')[-1].split(')')[0].replace(', ', ',')

'2015,11,12'

【讨论】:

    【解决方案2】:

    使用正则表达式替换找到带括号的字符串的一部分,然后替换其中的空格:

    import re
    
    tests = ["191, 4296092, datetime.date(2015, 11, 12), '2017-10-17 14:20:50.0', '&V101OLDOC'",
             "1, 2, (3, 4, 5), 6, 7, (8, 9, 10, 11), 12, 13"]
    
    for s in tests:
        s = re.sub(r'\(.*?\)',lambda m: m.group(0).replace(' ',''),s)
        print(s)
    
    191, 4296092, datetime.date(2015,11,12), '2017-10-17 14:20:50.0', '&V101OLDOC'
    1, 2, (3,4,5), 6, 7, (8,9,10,11), 12, 13
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-06
      • 2019-12-21
      • 1970-01-01
      • 2013-11-04
      • 2012-11-19
      • 2011-12-07
      • 2023-03-22
      相关资源
      最近更新 更多