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
  • 313,408
  • 56
  • 485
  • 544
jdyg
  • 681
  • 2
  • 8
  • 15

2 Answers2

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])
Fabien
  • 11,256
  • 8
  • 40
  • 62
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.

Ber
  • 37,567
  • 15
  • 65
  • 82