[Tutor] Space the final frontier!

Matthew White mwhite3 at ttsd.k12.or.us
Wed Apr 5 01:28:38 CEST 2006


Hi John,

It would be easier to do all of your whitespace elimination before you
append the string to your list(s).

Something like this I should get you started:

for line in input.readlines():
	line = re.sub('[\s]+', '', line)

	listy.append(line)

print listy

bonus points for appending the return from re.sub to your list.  :)

-mtw

On Tue, Apr 04, 2006 at 10:33:18PM +0100, John Corry (john.corry at ntlworld.com) wrote:
> Dear All,
> 
> I am having difficulty removing white spaces from my file.  The file is 999
> lines long and looks like the sample below:
> 
> 001, new field,dial= 028 90 79 0154, dial=
> 002, borfiled, dial= 02890 618521, dial=
> 003, newcomp, dial=02890419689, dial=
> 
> The program, I am using to import the file does not like the spaces around
> the numbers.  The number should look like the "dial=02890419689" in the
> third line.  Thus the sample above should look like:
> 
> 001,newfield,dial=02890790154,dial=
> 002,borfiled,dial=02890618521,dial=
> 003,newcomp,dial=02890419689,dial=
> 
> I have searched the tutor mailbag already and have picked up some good tips
> on join, split and re but I can't seem to get it to work.
> 
> I am using the following code.
> 
> filename = "c:/test.txt"
> import string
> import os
> import re
> listy = []
> input = open( filename, 'r')	#read access
> for line in input.readlines():
>     y = line
>     listy.append(y)
>     print listy
>     x = listy.pop()
> 
>     re.sub(r'\s', '', x)
>     print y,x
> 
> del input
> 
> It produces the output:
> 
> ['001, new field,dial= 028 90 79 0154, dial=\n']
> 001, new field,dial= 028 90 79 0154, dial=
> 001, new field,dial= 028 90 79 0154, dial=
> 
> ['002, borfiled, dial= 02890 618521, dial=\n']
> 002, borfiled, dial= 02890 618521, dial=
> 002, borfiled, dial= 02890 618521, dial=
> 
> ['003, newcomp, dial=02890419689, dial=']
> 003, newcomp, dial=02890419689, dial= 003, newcomp, dial=02890419689, dial=
> 
> Any help would be greatly appreciated.
> 
> Regards,
> 
> John.
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 
Matthew White - District Systems Administrator
Tigard/Tualatin School District
503.431.4128

"The greatest thing in this world is not so much where we are, but in
what direction we are moving."   -Oliver Wendell Holmes



More information about the Tutor mailing list