[Tutor] how to strip whitespaces from a string.

Kent Johnson kent_johnson at skillsoft.com
Fri Oct 8 19:33:59 CEST 2004


string.strip() just removes whitespace from the ends of the string.

If you just want to replace spaces within the string you can use 
string.replace():
 >>> s = "   I am learning\tpython    "
 >>> s.replace(' ', '')
'Iamlearning\tpython'

If you want to replace all whitespace characters then use re.sub():
 >>> import re
 >>> re.sub(r'\s', '', s)
'Iamlearningpython'

Kent

At 10:24 AM 10/8/2004 -0700, kumar s wrote:
>Thank you.
>  But I messed up my question.
>s = "   I am learning python    "
>f = s.strip()
>f
>'I am learning python'
>
>How can I get the ouput to:
>
>'Iamlearningpython'.
>
>That mean how can i remove whitespaces between words
>in a line and join all the words.
>
>sorry for asking twisted question.
>
>Thank you.
>kumar
>
>--- Calum Mackay <calum.mackay at cdmnet.org> wrote:
>
> > kumar s wrote:
> > > Dear group,
> > >  I have been practising python for some time now
> > and
> > > string method 'strip' always remains an alien to
> > me.
> > > whenever i try to use it, i never got what i want
> > and
> > > now it still remainins an enigma.
> > >
> > > s = " I am learning python"
> > >
> > > how can i remove white spaces from 's'.
> > >
> > > f = s.strip('\w') - wrong
> >
> > Do you want to strip trailing and leading ws only?
> > If so, then you just
> > want:
> >
> >       f = s.strip()
> >
> > since that's what strip() does by default.
> >
> > cheers,
> > c.
> >
>
>
>
>
>_______________________________
>Do you Yahoo!?
>Declare Yourself - Register online to vote today!
>http://vote.yahoo.com
>_______________________________________________
>Tutor maillist  -  Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor



More information about the Tutor mailing list