3

I'm trying to create a program where the user inputs a list of strings, each one in a separate line. I want to be able to be able to return, for example, the third word in the second line. The input below would then return "blue".

input_string("""The cat in the hat 
Red fish blue fish """)

Currently I have this:

def input_string(input):
    words = input.split('\n')

So I can output a certain line using words[n], but how do output a specific word in a specific line? I've been trying to implement being able to type words[1][2] but my attempts at creating a multidimensional array have failed.

I've been trying to split each words[n] for a few hours now and google hasn't helped. I apologize if this is completely obvious, but I just started using Python a few days ago and am completely stuck.

2
  • You need one more split on space. Commented Jul 18, 2013 at 19:30
  • 1
    Splitting on newlines gives a list of lines, then split a line on whitespace to a get a list of words on that line. Commented Jul 18, 2013 at 19:31

4 Answers 4

5

It is as simple as:

input_string = ("""The cat in the hat 
Red fish blue fish """)

words = [i.split(" ") for i in  input_string.split('\n')]

It generates:

[['The', 'cat', 'in', 'the', 'hat', ''], ['Red', 'fish', 'blue', 'fish', '']]
Sign up to request clarification or add additional context in comments.

Comments

1

It sounds like you want to split on os.linesep (the line separator for the current OS) before you split on space. Something like:

import os

def input_string(input)
   words = []
   for line in input.split(os.linesep):
       words.append(line.split())

That will give you a list of word lists for each line.

1 Comment

You probably shouldn't use os.linesep: stackoverflow.com/a/6165711/691859
1

There is a method called splitlines() as well. It will split on newlines. If you don't pass it any arguments, it will remove the newline character. If you pass it True, it will keep it there, but separate the lines nonetheless.

words = [line.split() for line in input_string.splitlines()]

Comments

0

Try this:

lines = input.split('\n')
words = []
for line in lines:
    words.append(line.split(' '))

In english:

  1. construct a list of lines, this would be analogous to reading from a file.
  2. loop over each line, splitting it into a list of words
  3. append the list of words to another list. this produces a list of lists.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.