0

I am having trouble splitting a string of characters into a list by the newline. My code:

i=raw_input().split("\n")

Does .split() do what I think it does? And if so, how do I get it to co-operate?

Here's my input as well:

>>>>>>v
^     v
^     >>>>X
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
The_Basset_Hound
  • 185
  • 1
  • 2
  • 11

3 Answers3

5

As given in the documentation -

raw_input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

It reads a single line from the input. If you want to read three lines from the input, you have to use three raw_input() , you can read the three raw_input() and append them to list . Example -

lst = [raw_input(), raw_input(), raw_input()]

Demo -

>>> lst = [raw_input(), raw_input(), raw_input()]
1
2
3
>>> lst
['1', '2', '3']

If you are redirecting standard input from a file or somewhere else, As mentioned in the comments by @KevinGuan , you can also use sys.stdin.read() to read the complete input at once and then do split on that. Example -

import sys
x = sys.stdin.read()
print(x.split('\n'))

A sample text file -

Blah
Blah1
blah2

Result -

python a.py < a.txt
['Blah', 'Blah1', 'blah2']

But please note, if you are redirecting from a file, I would rather use open() to read the file in python itself.

Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
3

I think that you would like to use sys.stdin.read():

import sys
data = sys.stdin.read()
data_list = data.strip().split('\n')

print data_list

output:

# here is the input:
>>>>>>v
^     v
^     >>>>X

# then press Ctrl+D on Linux, or Ctrl+Z on Windows
['>>>>>>v', '^     v', '^     >>>>X']
Remi Guan
  • 21,506
  • 17
  • 64
  • 87
  • This would be a perfect answer for [*How do I read multiple lines of raw input in Python?*](https://stackoverflow.com/q/11664443/3357935) – Stevoisiak Nov 02 '17 at 15:55
0

To read lines from a file into a Python list using your example input:

import fileinput

lines = [line.strip() for line in fileinput.input('input.txt')]

The output:

>>> lines
['>>>>>>v', '^     v', '^     >>>>X']
jasonrhaas
  • 1,083
  • 9
  • 11