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)'
I am expected to get this result:
>>> 'Flavor BLACKWATER OG (I), APPLE JACK (S), BLACKBERRY KUSH (I), SOUR TANGIE (S), SUNSET GELATO (H)'
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
.