Removing the continous newline characters from the pythong string

Discussion in 'Python' started by mobil, May 1, 2007.

  1. mobil

    mobil Guest

    Hi guys i m trying out newline characters and to clean them up
    a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf
    \n\nafs

    hello guys

    im trying to replace
    \n\n\n\n\n\n\n\n\n with \n

    thanks for help

    \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives
    \r carrriage returns

    thanks for any help or pointers
     
    mobil, May 1, 2007
    #1
    1. Advertising

  2. mobil

    Ian Clark Guest

    On 1 May 2007 14:30:12 -0700, mobil <> wrote:
    > Hi guys i m trying out newline characters and to clean them up
    > a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf
    > \n\nafs
    >
    > hello guys
    >
    > im trying to replace
    > \n\n\n\n\n\n\n\n\n with \n
    >
    > thanks for help
    >
    > \r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n also with \n as the browser gives
    > \r carrriage returns
    >
    > thanks for any help or pointers


    Is this what you were looking for?

    >>> import re
    >>> message = '\n\r\n\r\n\n\nhello there\n\r\n!\n'
    >>> regex = re.compile('[\n\r]+')
    >>> regex.sub('\n', s)

    '\nhello there\n!\n'

    Ian
     
    Ian Clark, May 1, 2007
    #2
    1. Advertising

  3. mobil

    Basilisk96 Guest

    why not use split:

    >>>s = " a\n\n\n\n\n\n\n\n\nsss\n\n\n\n\n\n\n\n\n\n\nvvvv\n\n\n\nvsa\n\n\n\nasf... \n\nafs"
    >>>s.split()

    ['a', 'sss', 'vvvv', 'vsa', 'asf...', 'afs']
     
    Basilisk96, May 1, 2007
    #3
  4. mobil

    Basilisk96 Guest

    What was I thinking? split() will only work if you have no other
    whitespace characters in the string. A regex like "[\n\r]+" is indeed
    much more appropriate and robust.

    Cheers
    -Basilisk96
     
    Basilisk96, May 1, 2007
    #4
    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. jordi
    Replies:
    0
    Views:
    408
    jordi
    Jul 16, 2003
  2. Jari Aalto+usenet
    Replies:
    0
    Views:
    388
    Jari Aalto+usenet
    Aug 19, 2003
  3. Hugh Beyer
    Replies:
    2
    Views:
    330
    Hugh Beyer
    Mar 17, 2006
  4. nirvana
    Replies:
    4
    Views:
    322
  5. celldee
    Replies:
    2
    Views:
    166
    celldee
    Apr 15, 2007
Loading...

Share This Page