首页 > 解决方案 > 在句点字符 (".") 后添加空格字符 (" ") 2 个字符空格?

问题描述

我们有一个将报告导出为 .txt 文件的旧系统,但在几乎所有提供日期的情况下,它都在货币面额之后,如下例所示: 25.0002/14/18 (25 bucks on feb 14th)287.4312/08/17.

有没有一种简单的方法来解析.并在右侧添加两个空格来分隔 Python 中的字符串?任何帮助是极大的赞赏!

标签: python-3.x

解决方案


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 /.


推荐阅读