Reputation: 758
I am trying to remove whitespaces at a particular region in a string to obtain a certain output.
The different sets of string that I have are:
gehehntk 45.5 % 43 - 83 5243 /g.mt 25674 - 65748
bin 9.6 md% 346347 - 36537
tub 31.8 % 3658 - 5585 calci
So the output I want is:
gehehntk 45.5 % 43-83 5243 /g.mt 25674-65748
bin 9.6 md% 346347-36537
tub 31.8 % 3658-5585 calci
I tried with a regex but was unable to achieve the output:
r"\b.*?\s(\d+(?:\.\d+)?)(?!\S)"
Upvotes: -2
Views: 101
Reputation: 427
If you only need to replace " - " by "-", you can use replace
s= """Polymorphs 60.3 % 40 - 80 5246 /c.mm 2000 - 7000
Haemoglobin 9.6 gm% 12.0 - 15.0
PCV 31.8 % 36 - 46 Calculated"""
print(s.replace (" - ", "-"))
Upvotes: 3
Reputation: 521093
We can try using re.sub
here:
inp = """Polymorphs 60.3 % 40 - 80 5246 /c.mm 2000 - 7000
Haemoglobin 9.6 gm% 12.0 - 15.0
PCV 31.8 % 36 - 46 Calculated"""
output = re.sub(r'\b(\d+)\s+-\s+(\d+)\b', r'\1-\2', inp)
print(output)
This prints:
Polymorphs 60.3 % 40-80 5246 /c.mm 2000-7000
Haemoglobin 9.6 gm% 12.0-15.0
PCV 31.8 % 36-46 Calculated
Upvotes: 0