How do I make my code discern how to divide my array?

Question:

I have to read this line from the text file:

Asta Ieva 5 0 17 10 23 23

The first two words are a name, all the others are different numbers. How do I make it so that that my program creates a list that goes like this: (name, number, number, number…)

Asked By: Rimants Šiupienis

||

Answers:

Start by using line.split(" ") to break up the individual words. Then you can use str.isdigit() to test which are names and which are numbers.

For example:

mylist = ["Number" if word.isdigit() else "Name" 
          for word in line.split(" ")]

If you need to split the array into names and numbers you could do something like

words = line.split(" ")
numbers = []
names = []
for word in words:
    if word.isdigit():
        numbers.append(int(word))
    else:
        names.append(word)
Answered By: Matthew B
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.