首页 > 解决方案 > 当数字后跟字母模式时,从字符串中删除数字

问题描述

我有三个字符串如下

ex1 = "All is good 24STREET"
ex2 = "Is this the weight 2.5OZ"
ex3 = "Feeling good 100pc"

我只想删除后面跟着“ OZ ”或“ pc ”的数字,而不是其他数字。

**results**
    ex1 = "All is good 24STREET"
    ex2 = "Is this the weight OZ"
    ex3 = "Feeling good pc"

我尝试使用' str.replace('\d+', '') ' 但这会删除所有数字而不是“点”

标签: pythonre

解决方案


import re

ex1 = "All is good 24STREET"
ex2 = "Is this the weight 2.5OZ"
ex3 = "Feeling good 100pc"
reg = re.compile(r'[\d.]+(?=OZ|pc)')
print(reg.sub('', ex1))
print(reg.sub('', ex2))
print(reg.sub('', ex3))

输出:

一切都好 24STREET

这是重量吗 OZ

感觉不错的电脑


推荐阅读