python - 删除小数点前的空格
问题描述
我对正则表达式有点陌生。我想将示例转换为hello coffee 0 .08 - 0 .24%
(hello coffee 0.08 - 0.24%
删除小数点前的空格并忽略其他情况)。你能建议一个正则表达式吗?
解决方案
使用re.sub
:
import re
for my_str in ['hello coffee 0 .08 - 0 .24%', 'hello coffee 0. 08 - 0. 24%']:
my_str = re.sub(r'(\d)\s*([.])\s*(\d)', '\\1\\2\\3', my_str)
print(my_str)
# hello coffee 0.08 - 0.24%
# hello coffee 0.08 - 0.24%