469,268 Members | 920 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,268 developers. It's quick & easy.

whitespace

RR
Is there an easy way in python to remove whitespace from a string?
Jul 18 '05 #1
5 51754
RR wrote:
Is there an easy way in python to remove whitespace from a string?

import string
"a b c".translate(string.maketrans("", ""), string.whitespace) 'abc'


Peter
Jul 18 '05 #2
Quoting RR (rr**@cornell.edu):
Is there an easy way in python to remove whitespace from a string?
Depending on what you mean by "remove whitespace":
mystring = " a b c d e f g "
mystring.strip() 'a b c d e f g' import re
re.sub("\s+", "", mystring)

'abcdefg'

--
http://mail.python.org/mailman/listinfo/python-list


--
Geoff Gerrietts "Whenever people agree with me I always
<geoff at gerrietts net> feel I must be wrong." --Oscar Wilde

Jul 18 '05 #3
On Fri, 19 Sep 2003 19:35:54 -0400, "RR" <rr**@cornell.edu> wrote:
Is there an easy way in python to remove whitespace from a string?


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
'hellothereworld'

Though there may be an easier way.


Jul 18 '05 #4
RR wrote:

Is there an easy way in python to remove whitespace from a string?

' string with whitespace '.strip()

'string with whitespace'

-Peter
Jul 18 '05 #5
"RR" <rr**@cornell.edu> wrote in message news:<pa****************************@cornell.edu>. ..
Is there an easy way in python to remove whitespace from a string?


' hello world '.replace(' ', '')

'helloworld'

Hung Jung
Jul 18 '05 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Thomas Mlynarczyk | last post: by
2 posts views Thread by Wolfgang Jeltsch | last post: by
2 posts views Thread by Carlitos | last post: by
2 posts views Thread by Carlitos | last post: by
3 posts views Thread by David Pratt | last post: by
9 posts views Thread by amattie | last post: by
5 posts views Thread by John Gordon | last post: by
13 posts views Thread by Chaim Krause | last post: by
1 post views Thread by CARIGAR | last post: by
reply views Thread by zhoujie | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.