0

I am having to read in from a file with lines in format '(Buy or Sell) (int representing number of stocks) (cost of stock)\n' and this was my solution on how to create a 2d array to access the different stuff later in the project.

with open(inputFile, 'r') as f:
    purchases = f.readlines()
    for line in purchases:
        tList.append(line).rstrip('\n'))
    for lineNum in range(0,len(tList)-1):
        tList[lineNum].split()
        #0 = 'Buy' or 'Sell', 1 = number of stocks, 2 = price per stock
        tList[lineNum][1] = eval(tList[lineNum][1])
        tList[lineNum][2] = eval(tList[lineNum][2])

When I run my code, this is the error message I get.

  File "project4.py", line 187, in <module>
    main()
  File "project4.py", line 103, in main
    tList[lineNum][1] = eval(tList[lineNum][1])
  File "<string>", line 1, in <module>
NameError: name 'u' is not defined

I assume that the .split function is splitting my line at every character and this is why it gets 'u' from 'Buy' I think the B is stored in tList[lineNum][0] but it cant eval the 'u'. I have no idea how to fix this and any help would be appreciated.

Udent
  • 7
  • 4

1 Answers1

1

split() doesn't split in-place, it creates a new list as a return value which you haven't assigned to anything. You're still working with the original string.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • Shouldn't it create a 2d array if i call it on a specific index of an array? – Udent Mar 07 '15 at 02:53
  • @Udent it's a method on a single string, and it returns a single list. – Mark Ransom Mar 07 '15 at 02:53
  • How could I split the string located at lineNum so it creates a list in that index spot? – Udent Mar 07 '15 at 02:56
  • OH, I understand, so the array was treating it all as a list. I edited the line to be tList[lineNum] = tList[lineNum].split() – Udent Mar 07 '15 at 02:57
  • Duplicate of [**Why doesn't calling a Python string method do anything unless you assign its output?**](http://stackoverflow.com/questions/9189172/why-doesnt-calling-a-python-string-method-do-anything-unless-you-assign-its-out) – smci Mar 07 '15 at 03:08
  • @Udent as a matter of style I wouldn't assign the results of `split` back to the same variable, otherwise that's it. And in Python, a list is just the official name of an array. – Mark Ransom Mar 07 '15 at 15:12