How can I add space in to several numbers?

Tim Chase python.list at tim.thechases.com
Mon Mar 2 15:12:58 EST 2009


> I want to parse a file and do this :
> 
>     A  74.335 -86.474-129.317  1.00 54.12
> 
> then add space between -86.474 and -129.317. I can get the file with
> 
>     A  74.335 -86.474 -129.317  1.00 54.12
> 
> How can I do this? Thanks.

Is there something wrong with the following?

   for line in file('in.txt'):
     line = line.replace('-', ' -')
     do_something(line)

calling line.split() on it will work the same way.  If not, you 
can use the regexp module to insert spaces between "a digit 
immediately followed by a dash":

   >>> s  = "A  74.335 -86.474-129.317  1.00 54.12"
   >>> s.replace('-', ' -')
   'A  74.335  -86.474 -129.317  1.00 54.12'
   >>> import re
   >>> r = re.compile(r'(\d)-')
   >>> r.sub(r'\1 -', s)
   'A  74.335 -86.474 -129.317  1.00 54.12'


-tkc







More information about the Python-list mailing list