python-3.x - 在句点字符 (".") 后添加空格字符 (" ") 2 个字符空格?
问题描述
我们有一个将报告导出为 .txt 文件的旧系统,但在几乎所有提供日期的情况下,它都在货币面额之后,如下例所示:
25.0002/14/18 (25 bucks on feb 14th)
或287.4312/08/17
.
有没有一种简单的方法来解析.
并在右侧添加两个空格来分隔 Python 中的字符串?任何帮助是极大的赞赏!
解决方案
The code below would add a space between the currency and the data given a string.
import re
my_file_text = "This is some text 287.4312/08/17"
new_text = re.sub("(\d+\.\d{2})(\d{2}/\d{2}/\d{2})", r"\1 \2", my_file_text)
print(new_text)
OUTPUT
'This is some text 287.43 12/08/17'
REGEX
(\d+\.\d{2})
: This part of the regex captures the currency in it's own group, it assumes that it will have any number of digits (>1) before the .
and then only two digits after, so something like (1000.25) would be captured correctly, while (1000.205) and (.25) won't.
(\d{2}/\d{2}/\d{2})
: This part captures the date, it assumes that the day, month and year portion of the dates will always be represented using two digits each and separated by a /.
推荐阅读
- minizinc - 半具体化的谓词是否被视为标准的一部分?
- python - tf.gather_nd 在 Keras 模型中使用时似乎有问题(在 'NoneType' 和 'int' 的实例之间不支持 '>' )
- python-3.x - 根据一行的值删除熊猫中数据框的特定行
- java - 如何编写带有两个带有过滤值的参数的@ParametrizedTest?
- javascript - 尝试将 formik 表单提交给操作
- python - 在 Python 中停止线程
- powershell - 如何使用 PowerShell 从本地目录中的 github 下载文件
- mysql - 从不同的表中选择元素。mysql
- google-cloud-platform - 如何知道批量云预测何时结束
- android-studio - 在颤振中没有为类“TextTheme”定义吸气剂“bodyText2”