Search code examples
pythontrimremoving-whitespace

Python: Removing random whitespace from a string of numbers


Tried a different number of combinations, none to avail.

Basically this is the string of numbers that I have:

20101002  100224   1    1044      45508  1001  1002  1003  1004  1005  1006

Output I'm after:

20101002 100224 1 1044 45508 1001 1002 1003 1004 1005 1006

Basically all whitespace before and after the last number have to be trimmed. On top of that there should only be one whitespace between the numbers.

I should add that the code I currently have is as follows and only deals with the whitespace at the start and end of the string:

row = line.strip().split(' ')

Any help is much appreciated, thanks!


Solution

  • this

    s = '20101002  100224   1    1044      45508  1001  1002  1003  1004  1005  1006'
    new_s = ' '.join(s.split())
    print(new_s)
    

    produces

    20101002 100224 1 1044 45508 1001 1002 1003 1004 1005 1006
    

    Basically, there are two steps involved:

    first we split the string into words with s.split(), which returns this list

    ['20101002', '100224', '1', '1044', '45508', '1001', '1002', '1003', '1004', '1005', '1006']
    

    then we pass the list to ' '.join, which joins all the elements of the list using the space character between them