Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
strip off just newlines
#1
so i have a string that might have multiple newlines at the end, or maybe a carriage-return line-feed pair. but i want the string with all of them removed. here's how i did it:
    line = line.splitlines()[0]
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
There is also str.rstrip()
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
#3
Hi,

Quote: here's how i did it:
But this way gives you a list as a result, not string... So either you need to join the list to a sting again or use the replacemethod of strings.

Regards, noisefloor
Reply
#4
(Jun-17-2019, 10:20 AM)noisefloor Wrote: Hi,

Quote: here's how i did it:
But this way gives you a list as a result, not string... So either you need to join the list to a sting again or use the replacemethod of strings.

Regards, noisefloor

It gives list but there is index used so the result is string.
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
#5
first, *rest = map(str.rstrip, line.splitlines())
This won't fail if you have only one line. Then the rest is an empty list.
If there are 0 lines, it will raise a ValueError, because there are not enough values (1) to unpack.

If you do this:
first = map(str.rstrip, line.splitlines())
Then first is an lazy evaluated map Iterator, not a sequence.

The top one works, because there is argument unpacking going on
and if this is the case, the iterable on the right side is consumed.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
(Jun-17-2019, 07:19 AM)perfringo Wrote: There is also str.rstrip()
str.rstrip() also removes trailing white spaces. while that is often good to do, there are some things that it is not right for. can you show the characters argument for str.rstrip() to get it to work the way i described?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#7
>>> help(str.rstrip)
Help on method_descriptor:

rstrip(self, chars=None, /)
    Return a copy of the string with trailing whitespace removed.
    
    If chars is given and not None, remove characters in chars instead.
(END)
>>> s = 'space and newline at end \n'
>>> s.rstrip('\n')
'space and newline at end '
>>> s = 'abc \n\n'
>>> s.rstrip('\n')
'abc '
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
#8
it might have spaces at the end that i want to keep.
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#9
(Jun-18-2019, 05:04 AM)Skaperen Wrote: it might have spaces at the end that i want to keep.

If there is space at end then original code will not handle them as well (splits on newline and takes only stuff before newline), so .rstrip() is in parity by functionality.

In case of removing some characters in arbitrary/all locations then str.replace and str.translate might be considered:

>>> help(str.replace)
Help on method_descriptor:

replace(self, old, new, count=-1, /)
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.
    
    If the optional argument count is given, only the first count occurrences are
    replaced.
(END)
>>> help(str.translate)
Help on method_descriptor:

translate(self, table, /)
    Replace each character in the string using the given translation table.
    
      table
        Translation table, which must be a mapping of Unicode ordinals to
        Unicode ordinals, strings, or None.
    
    The table must implement lookup/indexing via __getitem__, for instance a
    dictionary or list.  If this operation raises LookupError, the character is
    left untouched.  Characters mapped to None are deleted.
(END)
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
#10
if i have 'foobar \t\r\n' or 'foobar \t\n\n\n' then i want to end up with 'foobar \t'. if it fails because there is no newline then the previous code deal with it. my original use if this was in a program doing changes to a file.
    for line in stdin:
        line = line.splitlines()[0]
        ...
but i really should better handle the case of the last line of the file having end of file without a newline. if .splitlines() raises an exception in that case, then oops. but .rstrip() didn't preserve the ' \t' at the end of the line. where input has '\r\n' the output can just have '\n' which print() adds by default. but, maybe i should keep whatever newline the innput file has. i still need to process each line.
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,789 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
Smile please help me remove error for string.strip() jamie_01 3 1,149 Oct-14-2022, 07:48 AM
Last Post: Pedroski55
  Can't strip extra characters from Data Canflyguy 7 1,813 Jan-10-2022, 02:16 PM
Last Post: Canflyguy
  print not printing newlines rocket777 4 2,253 Jul-03-2021, 09:43 PM
Last Post: bowlofred
  strip() pprod 8 3,372 Feb-16-2021, 01:11 PM
Last Post: buran
  Need help with code for my WS2812B (Neopixel) Led Strip Phibbl 1 2,701 Apr-08-2020, 07:18 PM
Last Post: deanhystad
  split strip issues 'NonType' casacafe 8 3,759 Oct-08-2019, 06:29 PM
Last Post: ichabod801
  removing spaces/tabs after used .strip() zarize 0 1,552 Sep-11-2019, 12:46 PM
Last Post: zarize
  strip space from end of a row of text ineuw 4 2,822 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,371 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