[Tutor] How to remove a newline character

Lloyd Kvam pythontutor@venix.com
Sat, 06 Apr 2002 17:12:15 -0500


The regular expression processing is overkill for what you are trying to do.
The string.strip function removes all leading and trailing whitespace, which
includes spaces, tabs, and newlines.  Usually this is what you want to clean
up a data file.  Use string.rstrip to only remove the trailing whitespace.
string.whitespace lists the whitespace characters.

If you really want to only remove the linefeed from the end of a list of lines,
I would use:
lines = [line[:-1] for line in lines]
This simply chops off the last character.  Be sure to only do this once.

I use this function to get small data files for processing:
def stripFileLines( filename):
	infile = open( filename, 'r')	#read access
	contents = map(string.strip, infile.readlines())
	infile.close()
	return contents

tbrauch@tbrauch.com wrote:

>>Hi,
>>Can you please let me know  if it is possible to replace 
>>new line characters( '\n') in a list in one step?
>>
> 
> It's possible to replace it.  I don't know about in one step, but I was
> able to do it in two lines.
> 
> 
>>I have list like
>>
>>MyList=['272580\n', '23232432\n']
>>
>>and I would like to have 
>>,MyList=['272580', '23232432']
>>
>>so I tried
>>re.sub('\n','',MyList)
>>
> 
> That looks like the right pattern, but I think that re.sub only takes a
> string, not a list of strings.  (I might be wrong on this, though).
> 
> 
>>but I received 
>>TypeError: expected string or buffer
>>
> 
> Ah, yes, it looks like re.sub expected a string, not a list.
> 
> 
>>Your help would be appreciated
>>Thanks.
>>Ladislav
>>
> 
> So, we need to look at each string in the list.  This can be done with a
> for loop.
> 
> Let's try...
> Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
> 
>>>>MyList = ['272580\n', '23232432\n']
>>>>MyList2 = []
>>>>for item in MyList:
>>>>
> 	MyList2.append(re.sub('\n','',item))
> 
> 	
> 
>>>>MyList2
>>>>
> ['272580', '23232432']
> 
> 
> That seems to work.  re.sub was happy when I gave it a string, not a list
> of strings.
> 
> Another, yet less obvious way to try this, if the list is always numbers,
> is to do:
> 
> 
>>>>MyList = ['272580\n', '23232432\n']
>>>>MyList2 = []
>>>>for item in MyList:
>>>>
> 	MyList2.append(str(int(item)))
> 
> 	
> 
>>>>MyList2
>>>>
> ['272580', '23232432']
> 
> Then you don't have to worry about using re.
> 
> So, I couldn't do it in one step.  And, I had to create a new list to do
> it.  I'm sure someone out there is better and can improve on what I did.
> 
>  - Tim
> 
> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> 


-- 
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358

voice: 
603-443-6155
fax: 
801-459-9582