-1

I'm trying to figure out how to replace blocks of white space with a single character. I have a possibly poorly formatted file and I would like to unify the delimiter for the data. For instance:

3,4  5\t6 \t 7            8 9

would then become:

3,4,5,6,7,8,9

Something similar to this question but for python.

Community
  • 1
  • 1
nalyd88
  • 4,940
  • 8
  • 35
  • 51

3 Answers3

5
>>string = '4  5\t6 \t 7            8 9'
>>','.join(string.split())
>>'4,5,6,7,8,9'

see: Compress whitespaces in string

Community
  • 1
  • 1
NJM
  • 565
  • 3
  • 13
5

If you want regex:

    import re
    import sys
    line = sys.argv[1]
    re.sub(r'\s+', ',',line)
AmirC
  • 326
  • 5
  • 14
Thane Plummer
  • 7,966
  • 3
  • 26
  • 30
0

what about this

          string = "4  5\t6 \t 7            8 9"#your string
          a = string.split()
          print ', '.join(a)   #convert a list to string
Denis
  • 390
  • 3
  • 14