-2

I am trying to print by breaking a line based on character \n (new line). Below is the example:

line = "This is list\n 1.Cars\n2.Books\n3.Bikes"

I want to print the output as below:

This is list:
1.Cars
2.Books
3.Bikes

I used code as below:

line1 = line.split()
for x in line1:     
    print(x)        

But its printing each word in different line. How to split the string based on only "\n"

Regards, Arun Varma

Barmar
  • 741,623
  • 53
  • 500
  • 612
Varma403
  • 11
  • 1
  • 5

1 Answers1

1

The argument to split() specifies the string to use as a delimiter. If you don't give an argument it splits on any whitespace by default.

If you only want to split at newline characters, use

line1 = line.split('\n')

There's also a method specifically for this:

line1 = line.splitlines()
Barmar
  • 741,623
  • 53
  • 500
  • 612