Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 strip off just newlines
#11
(Jun-18-2019, 06:02 PM)Skaperen Wrote: if i have 'foobar \t\r\n' or 'foobar \t\n\n\n' then i want to end up with 'foobar \t'.

One can chain strip operations. However, it is error prone as depends on order:
>>> first = 'foobar \t\r\n'
>>> first.rstrip('\n').rstrip('\r') 
>>> 'foobar \t'
>>> second = 'foobar \t\n\n\n' 
>>> second.rstrip('\n').rstrip('\r') 
>>> 'foobar \t'
>>> third = 'foobar' 
>>> third.rstrip('\n').rstrip('\r')    
'foobar'
>>> fourth = 'foobar \n\r'
>>> fourth.rstrip('\n').rstrip('\r') 
>>> 'foobar \n'  
But if there are only two strips needed then one can do something 'clever' like this:

>>> fourth = 'foobar \t\n\r'
>>> cutouts = ('\n', '\r') 
>>> last = fourth.endswith('\r')
>>> previous = not last
>>> fourth.rstrip(cutouts[last]).rstrip(cutouts[previous]) 
'foobar \t'
>>> fifth = 'foobar \t\r\n'
>>> last = fifth.endswith('\r')
>>> previous = not last
>>> fourth.rstrip(cutouts[last]).rstrip(cutouts[previous])
'foobar \t'
It will not help in mixed case (\r\n\r\n).

After playing with code it seems to me that str.replace is more suitable for task at hand.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Quote
#12
i included the \t and \n in my need-example as alternate white space characters to show that i wanted splitting that includes these.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  split strip issues 'NonType' casacafe 8 283 Oct-08-2019, 06:29 PM
Last Post: ichabod801
  removing spaces/tabs after used .strip() zarize 0 163 Sep-11-2019, 12:46 PM
Last Post: zarize
  strip space from end of a row of text ineuw 4 400 Apr-15-2019, 03:14 AM
Last Post: ineuw
  How to remove whitespace from a string when .replace and .strip do not work winnetrie 7 692 Jan-05-2019, 08:44 AM
Last Post: DeaD_EyE
  Strip does not work when applied on a string read from a text file. susmis666 1 540 Dec-27-2018, 07:07 AM
Last Post: perfringo
  Why doesn't strip work? cybervigilante 5 964 Dec-27-2018, 02:21 AM
Last Post: metulburr
  Python with LED light strip question. Ostromaj 5 825 Aug-07-2018, 09:06 PM
Last Post: Ostromaj
  Search & Replace - Newlines Added After Replace dj99 3 728 Jul-22-2018, 01:42 PM
Last Post: buran
  need algorithm to strip non-ascii characters from LONG csv file hereathome 3 1,498 Jan-12-2018, 02:04 AM
Last Post: hereathome
  Best way to strip() after split() k357k9 11 4,260 Nov-03-2017, 03:39 PM
Last Post: k357k9

Forum Jump:


Users browsing this thread: 1 Guest(s)