Search code examples
pythonregexstringsubstringwhitespace

How to remove whitespaces at a particular region in a string in python?


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)"

Solution

  • 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 (" - ", "-"))