首页 > 解决方案 > 按照约定用特殊字符格式化字符串

问题描述

我正在处理的数据不干净,因此它包含不必要的空格,导致我的程序出现问题。我发现了以下案例:

- `chavs .` # (space before full stop)
- `band , this` # (space around comma, should be "band, stop")
- `needs ,continues` # (space before comma, should be "needs, continues")
- `51 %` # (space before percentage, should be "51%"
- `transfer :.` # (space before colon, should be "transfer:."
- `request,DDOS` # (no space around comma, should be "request, DDOS")
- `, , which` # (two commas together, should be ", which"

现在对于第一种情况,我将其转换为列表,然后删除空格,然后是''.join(arr). 数据很大,如果我通过转换为列表来处理每种情况,则会增加大量开销。是否有一种强大的、更通用的方式来处理这种情况(也许是一个好的正则表达式)?

标签: pythonpython-3.xstringstring-formatting

解决方案


我想说所有这些对于使用 .replace() 方法对您的数据进行修复非常简单,无需转换为列表。例如,案例 2 可以通过 .replace(" ,", ",") 来修复。


推荐阅读