0

I'm new at Python and I have an assginment which is read a file and convert it to matrix. My file is:

n 5
0 -- 3
0 -- 4
1 -- 2
1 -- 3
2 -- 4
3 -- 3

First of all,I have to make a "5X5" matrix. I read 5 like this:

f = open("graph.txt")
 mylist = f.readlines()
 a = mylist[0][2]

When say print a it prints 5. In order to make a matrix I need to convert this string to integer. However, when I used int(a) function, it remained a str. How can I change it to integer permanently?

Tim Pietzcker
338k59 gold badges521 silver badges572 bronze badges
asked Mar 4, 2013 at 8:58
5
  • 1
    You probably also want to look into the .split() method to split strings into chunks based on whitespace. That looks like a tool you're going to need. Commented Mar 4, 2013 at 9:06
  • What does the resultant matrix look like? Could you please post it? Commented Mar 4, 2013 at 9:08
  • Closely related: How to read numbers from file in Python? Commented Mar 4, 2013 at 9:09
  • When I use .split() for other lines, besides the first one, it splits last number (for example 3) with "3\n". How can I select just one item with this method? @TimPietzcker Commented Mar 4, 2013 at 9:12
  • Use mylist = [line.strip().split() for line in f]. Commented Mar 4, 2013 at 9:17

2 Answers 2

3

int creates a new value but does not change the original one. So, to actually change the value, you must do something like

list[0][2] = int(list[0][2])
answered Mar 4, 2013 at 9:00
Sign up to request clarification or add additional context in comments.

Comments

0

use the int() constructor to assign to a:

a = int(list[0][2])

Note that this will raise an exception if the string cannot be converted to int.

answered Mar 4, 2013 at 9:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.