-1

I have a text file which contains a table comprised of numbers e.g:

5,10,6
6,20,1
7,30,4
8,40,3
9,23,1
4,13,6

if for example I want the numbers contained only in the third column, how do i extract that column into a list?

I have tried the following:

myNumbers.append(line.split(',')[2])
  • What have you tried? Show us your code. This is a very easy task. Hint: the `csv` module. – Tim Roberts Sep 26 '22 at 23:00
  • I updated the question with what I have tried, but I do not want to use the csv module. – FrustratedSnake Sep 26 '22 at 23:02
  • 3
    What is `line`? Lists are zero-indexed in Python, so "third column" would be `[2]` – OneCricketeer Sep 26 '22 at 23:02
  • 3
    If you aren't using it - [csv](https://docs.python.org/3/library/csv.html) module would be preferred – OneCricketeer Sep 26 '22 at 23:03
  • @OneCricketeer He said he doesn't want to use that. Don't know why. – Barmar Sep 26 '22 at 23:05
  • 2
    Don't forget to strip off the newline from `line`. `line.strip().split(',')[2]` – Barmar Sep 26 '22 at 23:05
  • 3
    Why don't you want to use the csv module? – Barmar Sep 26 '22 at 23:06
  • Welcome to Stack Overflow! Please take the [tour]. What happened when you tried that? You probably got `IndexError: list index out of range`, right? If so, then I suppose this is a duplicate of [this existing question](/q/1098643/4518341), which I found by googling the error message. If not, then we need more details: please make a [mre] including enough code to reproduce the problem and the full error message. BTW, for more tips, see [ask]. – wjandrea Sep 26 '22 at 23:15
  • Curiosity, I'm new to python and I only know how to do things without relying on specific modules. The strip method was what I was looking for. – FrustratedSnake Sep 27 '22 at 00:38
  • The beauty of Python is its extensive standard library. You NEED to rely on the standard modules. They are what make Python programming efficient. – Tim Roberts Sep 27 '22 at 01:29

1 Answers1

0

The strip method will make sure that the newline character is stripped off. The split method is used here to make sure that the commas are used as a delimiter.

line.strip().split(',')[2]