Is there an easy way in python to remove whitespace from a string?
whitespace
Collapse
This topic is closed.
X
X
-
RRTags: None -
Peter Otten
Re: whitespace
RR wrote:
[color=blue]
> Is there an easy way in python to remove whitespace from a string?[/color]
[color=blue][color=green][color=darkred]
>>> import string
>>> "a b c".translate(st ring.maketrans( "", ""), string.whitespa ce)[/color][/color][/color]
'abc'[color=blue][color=green][color=darkred]
>>>[/color][/color][/color]
Peter
-
Geoff Gerrietts
Re: whitespace
Quoting RR (rr84@cornell.e du):[color=blue]
> Is there an easy way in python to remove whitespace from a string?[/color]
Depending on what you mean by "remove whitespace":
[color=blue][color=green][color=darkred]
>>> mystring = " a b c d e f g "
>>> mystring.strip( )[/color][/color][/color]
'a b c d e f g'[color=blue][color=green][color=darkred]
>>> import re
>>> re.sub("\s+", "", mystring)[/color][/color][/color]
'abcdefg'
[color=blue]
> --
> http://mail.python.org/mailman/listinfo/python-list[/color]
--
Geoff Gerrietts "Whenever people agree with me I always
<geoff at gerrietts net> feel I must be wrong." --Oscar Wilde
Comment
-
Tim Rowe
Re: whitespace
On Fri, 19 Sep 2003 19:35:54 -0400, "RR" <rr84@cornell.e du> wrote:
[color=blue]
>Is there an easy way in python to remove whitespace from a string?[/color]
From the ends or all of it?
From the ends,
" hello ".strip()
gives "hello"
There are lstrip and rstrip if you only want to strip from one end.
To get rid of all whitespace I'd probably do:
import string
string.join(" hello there world ".split(), "")
which gives
'hellothereworl d'
Though there may be an easier way.
Comment
-
Peter Hansen
Re: whitespace
RR wrote:[color=blue]
>
> Is there an easy way in python to remove whitespace from a string?[/color]
[color=blue][color=green][color=darkred]
>>> ' string with whitespace '.strip()[/color][/color][/color]
'string with whitespace'
-Peter
Comment
-
Hung Jung Lu
Re: whitespace
"RR" <rr84@cornell.e du> wrote in message news:<pan.2003. 09.19.23.35.54. 334022@cornell. edu>...[color=blue]
> Is there an easy way in python to remove whitespace from a string?[/color]
' hello world '.replace(' ', '')
'helloworld'
Hung Jung
Comment
Comment