Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a list from another list - Python

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.

like image 898
eltb Avatar asked Mar 08 '26 08:03

eltb


2 Answers

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', '']]
like image 189
jabaldonedo Avatar answered Mar 09 '26 22:03

jabaldonedo


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.

like image 22
Tom Avatar answered Mar 10 '26 00:03

Tom