whitespace

Discussion in 'Python' started by RR, Sep 20, 2003.

  1. RR

    RR Guest

    Is there an easy way in python to remove whitespace from a string?
     
    RR, Sep 20, 2003
    #1
    1. Advertising

  2. Quoting RR ():
    > 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
     
    Geoff Gerrietts, Sep 20, 2003
    #2
    1. Advertising

  3. RR

    Peter Otten Guest

    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
     
    Peter Otten, Sep 20, 2003
    #3
  4. RR

    Tim Rowe Guest

    On Fri, 19 Sep 2003 19:35:54 -0400, "RR" <> 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.
     
    Tim Rowe, Sep 20, 2003
    #4
  5. RR

    Peter Hansen Guest

    RR wrote:
    >
    > Is there an easy way in python to remove whitespace from a string?


    >>> ' string with whitespace '.strip()

    'string with whitespace'

    -Peter
     
    Peter Hansen, Sep 20, 2003
    #5
  6. RR

    Hung Jung Lu Guest

    "RR" <> wrote in message news:<>...
    > Is there an easy way in python to remove whitespace from a string?


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

    'helloworld'

    Hung Jung
     
    Hung Jung Lu, Sep 20, 2003
    #6
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. threecrans
    Replies:
    0
    Views:
    1,456
    threecrans
    Jul 3, 2003
  2. Donal McWeeney

    Div control and additional whitespace

    Donal McWeeney, Oct 17, 2003, in forum: ASP .Net
    Replies:
    2
    Views:
    336
    Donal McWeeney
    Oct 20, 2003
  3. Oli Filth
    Replies:
    9
    Views:
    3,358
    Uncle Pirate
    Jan 17, 2005
  4. Replies:
    10
    Views:
    781
    Eric Brunel
    Dec 16, 2008
  5. MRAB
    Replies:
    3
    Views:
    398
Loading...

Share This Page