python - 按照约定用特殊字符格式化字符串
问题描述
我正在处理的数据不干净,因此它包含不必要的空格,导致我的程序出现问题。我发现了以下案例:
- `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)
. 数据很大,如果我通过转换为列表来处理每种情况,则会增加大量开销。是否有一种强大的、更通用的方式来处理这种情况(也许是一个好的正则表达式)?
解决方案
我想说所有这些对于使用 .replace() 方法对您的数据进行修复非常简单,无需转换为列表。例如,案例 2 可以通过 .replace(" ,", ",") 来修复。
推荐阅读
- c# - C# 中带字节的运算符 << 和 >>
- python - 需要帮助在 python 中更快地进行总和计算
- php - 如何使用连接来选择返回消息行的类似计数
- javascript - 在 Laravel 5 中包含外部 css 和 JS 文件
- html - 在 vue 组件中使用样式的最佳实践是什么?
- javascript - 如何在使用响应作为参数的 fech 之后从动作创建者重定向?
- python - 试图从列中获取毫秒并转换为日期格式
- apache-nifi - 公共网络中的 Nifi 安全性
- arrays - 在 Swift Xcode 中为每个数组项生成一个单独的页面
- c# - 我正在尝试运行一个循环,但我遇到了一个我不知道如何修复的错误