Python:数字在字母后保留空格后替换空格

Cou*_*unt 4 python regex

作为预处理数据的一部分.我希望能够替换空格后跟一个数字,保持空格后跟一个字符.例如:

Input String: '8.1.7 Sep 2000 Dec 2004 Dec 2006 Indefinite'

Expected output: '8.1.7,Sep 2000,Dec 2004,Dec 2006,Indefinite'
Run Code Online (Sandbox Code Playgroud)

我在python中使用基于正则表达式的替换函数:

re.sub("\s+", ",", release) 
Run Code Online (Sandbox Code Playgroud)

但这并没有取得理想的结果,只是因为这意味着要替换所有空格,不知道如何保持一个字符后跟即[a-z].

或许我需要重新思考方法.

Wik*_*żew 7

您可以使用a (?<=\d)在空格之前要求数字:

release = re.sub(r"(?<=\d)\s+", ",", release)
Run Code Online (Sandbox Code Playgroud)

请参阅正则表达式演示

细节

  • (?<=\d) - 一个积极的外观,需要一个数字立即出现在当前位置的左侧
  • \s+ - 一个或多个空格字符.