[Tutor] Problem Stripping

Steven D'Aprano steve at pearwood.info
Mon Apr 2 03:40:32 CEST 2012


leam hall wrote:
> Python 2.4.3 on Red Hat 5. Trying to use strip to remove characters
> but it doesn't seem to work like I thought.
> 
> 
> res = subprocess.Popen(['uname', '-a'], stdout=subprocess.PIPE)
> uname = res.stdout.read().strip()

For future reference, you should identify the shortest possible amount of code 
that demonstrates the problem. See also http://sscce.org/

You are asking a question about string.strip(). Where the string comes from is 
irrelevant -- there's no need to use an example as complicated as the above, 
when a simple string constant will do the job perfectly. So the shortest 
possible amount of code to demonstrate your problem is a single method call:

 >>> 'spam ham 1:2:3 eggs'.strip(':')
'spam ham 1:2:3 eggs'


All the stuff with subprocess.Popen and reading from stout and whatnot doesn't 
have anything to do with the issue at hand. It cannot shed any light on the 
problem; at best it must be ignored, at worst it may confuse the issue.

As others have already explained, strip() does not remove characters from 
anywhere in the string, it strips them from the ends only.

There is also a lstrip() and rstrip() for times you only want to remove them 
from the left or right side.



-- 
Steven



More information about the Tutor mailing list