Python Forum
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.
Reply
#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.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  extract only text strip byte array Pir8Radio 7 2,921 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
Smile please help me remove error for string.strip() jamie_01 3 1,194 Oct-14-2022, 07:48 AM
Last Post: Pedroski55
  Can't strip extra characters from Data Canflyguy 7 1,859 Jan-10-2022, 02:16 PM
Last Post: Canflyguy
  print not printing newlines rocket777 4 2,292 Jul-03-2021, 09:43 PM
Last Post: bowlofred
  strip() pprod 8 3,450 Feb-16-2021, 01:11 PM
Last Post: buran
  Need help with code for my WS2812B (Neopixel) Led Strip Phibbl 1 2,757 Apr-08-2020, 07:18 PM
Last Post: deanhystad
  split strip issues 'NonType' casacafe 8 3,849 Oct-08-2019, 06:29 PM
Last Post: ichabod801
  removing spaces/tabs after used .strip() zarize 0 1,578 Sep-11-2019, 12:46 PM
Last Post: zarize
  strip space from end of a row of text ineuw 4 2,877 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 4,447 Jan-05-2019, 08:44 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020