【问题标题】:Removing the . (full-stop) and , (commas) that occurs in-between numbers in python删除 . (句号)和,(逗号)出现在python中的数字之间
【发布时间】:2019-10-30 16:34:06
【问题描述】:

如何删除 . (句号)和,(逗号)出现在python中的数字之间?

示例输入:“衬衫花费 1,50,0,外套花费 1.5.00,帽子花费 2.50。”

示例输出:“衬衫花费 1500,外套花费 1500,帽子花费 250。”

Remove period[.] and comma[,] from string if these does not occur between numbers 的解决方案与上述要求相反。

re.sub('[.,]','',input) 删除所有逗号和句号。

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    你可以使用这个模式

    (\d)[,.](\d)
    

    替换为\1\2

    Regex Demo

    如果有多个 . or , 的数字,您可以使用环视

    (?<=\d)[,.](?=\d)
    
    • (?&lt;=\d) - 匹配必须以数字字符开头
    • [,.] - 匹配 , or .
    • (?=\d) - 匹配必须后跟数字

    用空字符串替换

    Regex Demo

    【讨论】:

    • 对于1.5.00 的第二种情况不太适用(但在这里运行两次会起作用)-
    • @AshwinGeetD'Sa 你可以使用环视,看第二个模式
    • re.sub('(?&lt;=\d)[,.](?=\d)','',sentence)
    • @AshwinGeetD'Sa 也为第二种模式添加了进一步的解释
    • @Steve 我们也可以使用lookarounds,我也添加了一个带有lookaheads的模式
    猜你喜欢
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-24
    • 1970-01-01
    • 2018-05-30
    • 2013-05-27
    相关资源
    最近更新 更多