2

I want to print out a certain value from a list. Here is my code:

rdf_f = open("substrate.txt")
for line in rdf_f:
    fields = line.split()
    if len(fields) > 1:
        x = fields[1]
    print(x[2])

How can I correctly use the print() command to print out the 3rd value of x? Because I got an error:

IndexError: string index out of range

I know if x = [1,2,3,4,5,6], my code works. But here x is a perpendicular column. When I use print(x), the output is

0
1
2
3
4
5
6
7
8
9
10
0
1
2
3
4
5
6
7
8
9
10
...
10
  • If you replace print(x[2]) with print(x), what do you get? Commented Sep 18, 2013 at 15:37
  • Your x is a string and not a list! Because you assign the second string of the list fileds to it. Commented Sep 18, 2013 at 15:38
  • @thegrinner A column that I described in the question Commented Sep 18, 2013 at 15:42
  • You are only assigning x a single value (the second one in your list you recieve by the line.split() function). BTW: You're code will also fail, when - for example - len(fields) <= 1 on the first call, because you want to print x which has never been assigned a value. Commented Sep 18, 2013 at 15:43
  • 1
    Could you post the full content of x (print(x)) right before the error occurs? Commented Sep 18, 2013 at 15:51

2 Answers 2

5

You got that error because there are no items at that index. So you better use for loop. And print all items.

for item in fields:
    print item

OR

Check for the length of fields list and print accordingly.

   if len(fields)>3:
      print fields[3]
Sign up to request clarification or add additional context in comments.

1 Comment

+1. It is often the problem when a text file is read. It often happens that the last line of a text file is the empty line that is not visible in editor by naked eye.
1

Your list is fields, not x. Perhaps the value you are looking for is fields[2]

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.