Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "split" on empty new line

Tags:

python

Trying to use a python split on a "empty" newline but not any other new lines. I tried a few other example I found but none of them seem to work.

Data example:

(*,224.0.0.0/4) RPF nbr: 96.34.35.36 Flags: C RPF P
  Up: 1w6d

(*,224.0.0.0/24) Flags: D P
  Up: 1w6d

(*,224.0.1.39) Flags: S P
  Up: 1w6d

(96.34.246.55,224.0.1.39) RPF nbr: 96.34.35.36 Flags: RPF
  Up: 1w5d
  Incoming Interface List
    Bundle-Ether434 Flags: F A, Up: 1w5d
  Outgoing Interface List
    BVI100 Flags: F, Up: 1w5d
    TenGigE0/0/0/3 Flags: F, Up: 1w5d
    TenGigE0/0/1/1 Flags: F, Up: 1w5d
    TenGigE0/0/1/2 Flags: F, Up: 1w5d
    TenGigE0/0/1/3 Flags: F, Up: 1w5d
    TenGigE0/1/1/1 Flags: F, Up: 1w5d
    TenGigE0/1/1/2 Flags: F, Up: 1w5d
    TenGigE0/2/1/0 Flags: F, Up: 1w5d
    TenGigE0/2/1/1 Flags: F, Up: 1w5d
    TenGigE0/2/1/2 Flags: F, Up: 1w5d
    Bundle-Ether234 (0/3/CPU0) Flags: F, Up: 3d16h
    Bundle-Ether434 Flags: F A, Up: 1w5d

I want to split on anything that is a new line online and only a newline.

Example code is below:

myarray = []
myarray = output.split("\n")
for line in myarray:
    print line
    print "Next Line"

I am do have the "re" library imported.

like image 854
DJ Otter Avatar asked Aug 09 '16 13:08

DJ Otter


People also ask

How do you split text in an empty line in Python?

To split text by empty line, split the string on two newline characters, e.g. my_str. split('\n\n') for POSIX encoded files and my_str. split('\r\n\r\n') for Windows encoded files.

How do you split data in new line in Python?

To split a string by newline character in Python, pass the newline character "\n" as a delimiter to the split() function. It returns a list of strings resulting from splitting the original string on the occurrences of a newline, "\n" .

How do you get rid of the extra line in Python?

strip() Python String strip() function will remove leading and trailing whitespaces. If you want to remove only leading or trailing spaces, use lstrip() or rstrip() function instead.

Does Split always return a list?

split() Return ValueThe return value of the split() method is always a list of strings obtained after breaking the given string by the specified separator.


1 Answers

It's quite easy when you consider what is on an empty line. It's just the newline character, so splitting on an empty line would be splitting on two newline characters in sequence (one from the previous non-empty line, one is the 'whole' empty line.

myarray = output.split("\n\n")
for line in myarray:
    print line
    print "Next Line"

and for Python 3:

myarray = output.split("\n\n")
for line in myarray:
    print(line)
    print("Next Line")

If you want to be platform-agnostic, use os.linesep + os.linesep instead of "\n\n", as is mentioned in Lost's answer.

like image 99
Kiraa Avatar answered Sep 23 '22 03:09

Kiraa