python - 当数字后跟字母模式时,从字符串中删除数字
问题描述
我有三个字符串如下
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+', '') ' 但这会删除所有数字而不是“点”
解决方案
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
感觉不错的电脑
推荐阅读
- c# - 如果字段和方法是静态的,为什么新建一个类的实例毫无意义/毫无意义?[C#]
- java - How to initalize a PGpolygon using a String Java
- python - 在python中使用哈希表(字典)查找对称对
- ios - 如何从某个百分比获得贝塞尔路径的分数
- sqlite - SQLite: Create blobs table from SELECT WHERE query
- c++ - 设备串行通信期间的意外行为
- javascript - NGXS 在 setState 中传播状态
- r - 通过 R 从 Premium API 通过 rtweet 下载历史推文
- pandas - 如何在 tkiner 窗口中打开文件,而不是让脚本的其他功能可以访问它
- avro - avro 1.8.2 日期类型和拼花书写