re.sub replace spaces with comma

41,115

To remove the leading and trailing spaces you can use .strip(), and then to replace consecutive whitespace characters using the regular expression \s+:

>>> import re
>>> s = " 2.4       -2.0           4.3"
>>> re.sub("\s+", ",", s.strip())
'2.4,-2.0,4.3'
Share:
41,115
marco
Author by

marco

Updated on July 19, 2022

Comments

  • marco
    marco almost 2 years

    I have a list of items which look like so:

     2.4       -2.0           4.3
    -6.0       12.5           1.0
    

    What I would like is to remove all those spaces and replace them with "," (comma) except for the spaces in front of first numbers (they should be just deleted (the spaces) and not replaced with anything). So the upper string items should look like so, after replacement:

    2.4,-2.0,4.3
    -6.0,12.5,1.0
    

    Not like this:

    ,2.4,-2.0,4.3
    ,-6.0,12.5,1.0
    

    Which is what the following code does:

    newStrings = []
    for s in strings:
        newStrings.append(re.sub('\s+', ',', s))
    

    What regular expression for re.sub should be used to achieve that? Thank you.

  • marco
    marco over 9 years
    Thank you Daniel. Is there some beginner friendly tutorial on regular expression? I tried this one, but looks to complicated for my level of knowledge: tutorialspoint.com/python/python_reg_expressions.htm
  • DanielGibbs
    DanielGibbs over 9 years
    There are many, but one written for Python is docs.python.org/2/howto/regex.html.
  • marco
    marco over 9 years
    Checked that one too. Sometimes I have a feeling that people who do not want other people to learn Python, write these kinds of documentations. Thank you though.
  • DanielGibbs
    DanielGibbs over 9 years
    No problem. If the answer solved your problem would you mind marking it as the accepted answer? (Click the check mark)