python re how to give space after specific word?

Viewed 90

I am trying to add space after word 'Flavor' but getting space after every letter. here is my code:

re.sub(r'(?<=["Flavor"])(?=[^\s])', r' ', short_description)

my python shell result >>>'F l a v o r BLACKWATER OG (I), APPLE JACK (S), BLACKBERRY KUSH (I), SOUR TANGIE (S), SUNSET GELATO (H), GORILLA GLUE 4 (H), GRAND DADDY PURP (I), WHITE WIDOW (S), NAPALM OG (I)'

I am expected to get this result:

'Flavor BLACKWATER OG (I), APPLE JACK (S), BLACKBERRY KUSH (I), SOUR TANGIE (S), SUNSET GELATO (H), GORILLA GLUE 4 (H), GRAND DADDY PURP (I), WHITE WIDOW (S), NAPALM OG (I)'
1 Answers

Use re.sub with a regex shown below to replace every occurrence of Flavor followed by 0 or more whitespace characters with Flavor (which has exactly 1 blank after Flavor):

import re
short_descriptions = [
    'FlavorBLACKWATER OG',
    'Flavor BLACKWATER OG',
    'Flavor  BLACKWATER OG'
]
for short_description in short_descriptions:
    print(re.sub(r'Flavor\s*', r'Flavor ', short_description))

Prints:

Flavor BLACKWATER OG
Flavor BLACKWATER OG
Flavor BLACKWATER OG

Note that the regex above avoids the lookbehind ((?<=Flavor )) completely.
Also note that as the commenters above mentioned, the regex you were using specifies a character class ["Flavor"], so adds a blank after any of these specified characters: ", F, l, a, v, o, r.

Related