Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python : replacing a space after numbers keeping space after letters

Tags:

python

regex

As part of preprocessing my data. I want to be able to replace space followed by a number, keeping the space followed by a character. For example:

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

Expected output: '8.1.7,Sep 2000,Dec 2004,Dec 2006,Indefinite'

I am using the regular expression based replace function in python:

re.sub("\s+", ",", release) 

but this is not fetching the desired result, simply because this meant to replace all spaces, not sure how to keep the one followed by characters i.e. [a-z].

Or maybe I need to rethink on approach.

like image 416
Count Avatar asked Dec 19 '22 00:12

Count


1 Answers

You may use a (?<=\d) to require a digit before the whitespace:

release = re.sub(r"(?<=\d)\s+", ",", release)

See the regex demo

Details

  • (?<=\d) - a positive lookbehind that requires a digit to appear immediately to the left of the current location
  • \s+ - 1 or more whitespace chars.
like image 197
Wiktor Stribiżew Avatar answered Dec 27 '22 02:12

Wiktor Stribiżew