【问题标题】:Remove parentheses around integers in a string删除字符串中整数周围的括号
【发布时间】:2015-12-12 22:53:04
【问题描述】:

我想在这样的表达式中将 (number) 替换为 number

4 + (3) - (7)

应该是:

4 + 3 - 7

如果表达式是:

2+(2)-(5-2/5)

应该是这样的:

2+2-(5-2/5)

我试过了

a = a.replace(r'\(\d\+)', '')

其中a 是一个字符串,但它不起作用。谢谢!

【问题讨论】:

    标签: python regex string


    【解决方案1】:

    Python 有一个强大的正则表达式模块re,具有替换方法:

    >>> import re
    >>> a = '2+(2)-(5-2/5)'
    >>> re.sub('\((\d+)\)', r'\1', a)
    '2+2-(5-2/5)'
    

    【讨论】:

    • @DusanMilosevic:如果答案有帮助,请记住接受它。
    • 哦,是的,我一小时左右都接受不了,我忘了。对不起
    猜你喜欢
    • 2020-08-18
    • 2019-03-01
    • 1970-01-01
    • 2018-10-29
    • 2020-05-28
    • 1970-01-01
    • 2023-03-24
    • 2012-03-16
    相关资源
    最近更新 更多