Reputation: 33
I want to replace certain characters in a string like below:
Input string:
s = "1kgbutter2kilochilli30gmssalt"
Output string:
s = " 1kg butter 2kilo chilli 30gms salt"
I have tried using re.sub
like below but no luck.
re.sub(r"^[0-9]*(kg|kilo|gm)s$", "*how do i add spaces if exp matches*", s)
Upvotes: 2
Views: 199
Reputation: 626804
You can use
re.sub(r'\d+(?:kg|kilo|gm)s?', r' \g<0> ', s)
NOTE: If you need to avoid the resulting spaces at the start or end of string, add .strip()
at the end of the re.sub
.
See the regex demo. Details:
\d+
- one or more digits(?:kg|kilo|gm)
- kg
, kilo
or gm
s?
- an optional s
char.The \g<0>
is a backreference that inserts the whole match back into the resulting string.
See this Python demo:
import re
s = "1kgbutter2kilochilli30gmssalt"
print( re.sub(r'\d+(?:kg|kilo|gm)s?', r' \g<0> ', s).strip() )
# => 1kg butter 2kilo chilli 30gms salt
Upvotes: 1