50

I cannot figure out a problem I am having with code written in Python 2.7. I am converting the references to ints, but I keep getting a type exception bad operand type for unary +: 'str'. Can anyone assist?

import urllib2
import time
import datetime

stocksToPull = 'EBAY', 'AAPL'


def pullData(stock):
    try:
        print 'Currently pulling', stock
        print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
        urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + \
            stock + '/chartdata;type=quote;range=3y/csv'
        saveFileLine = stock + '.txt'

        try:
            readExistingData = open(saveFileLine, 'r').read()
            splitExisting = readExistingData.split('\n')
            mostRecentLine = splitExisting[-2]
            lastUnix = mostRecentLine.split(',')[0]
        except Exception, e:
            print str(e)
            time.sleep(1)
            lastUnix = 0

        saveFile = open(saveFileLine, 'a')
        sourceCode = urllib2.urlopen(urlToVisit).read()
        splitSource = sourceCode.split('\n')

        for eachLine in splitSource:
            if 'values' not in eachLine:
                splitLine = eachLine.split(',')
                if len(splitLine) == 6:
                    if int(splitLine[0]) > int(lastUnix):
                        lineToWrite = eachLine + '\n'
                        saveFile.write(lineToWrite)
        saveFile.close()

        print 'Pulled', + stock
        print 'Sleeping....'
        print str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S'))
        time.sleep(120)

    except Exception, e:
        print 'main loop', str(e)


for eachStock in stocksToPull:
    pullData(eachStock)

I am hitting the operand exception bad operand type for unary +: 'str' when it gets to if int(splitLine[0]) > int(lastUnix): even though both values being compared print out as ints when tested. can anyone give me some feedback? thank you!

here is the exception response:

Currently pulling EBAY
2013-12-21 11:32:40
Pulled main loop bad operand type for unary +: 'str'
Currently pulling AAPL
2013-12-21 11:32:41
Pulled main loop bad operand type for unary +: 'str'`
xiº
  • 4,605
  • 3
  • 28
  • 39
heinztomato
  • 795
  • 1
  • 7
  • 12
  • 3
    Don't just catch an exception to print it, because you lose the stack trace! – Eric Dec 21 '13 at 17:28
  • 1
    Note that this will also happen if you try to concatenate a string that u use in conditional check. For example `if string1: res = string1 + 'moreText'` – Jun Sep 06 '18 at 21:51
  • 8
    For those who landed on this page: if you `_str += str1 + str2 + + str3` you'll get this same error. Notice the `+ +` with nothing in between. – Joshua Burns Jul 16 '19 at 02:47
  • @JoshuaBurns this solved my reason for reading this post. Sometimes it's the little syntax things that get ya; in my case, it was a stray comma. thx – endorpheus Mar 31 '21 at 01:57

3 Answers3

51

You say that if int(splitLine[0]) > int(lastUnix): is causing the trouble, but you don't actually show anything which suggests that. I think this line is the problem instead:

print 'Pulled', + stock

Do you see why this line could cause that error message? You want either

>>> stock = "AAAA"
>>> print 'Pulled', stock
Pulled AAAA

or

>>> print 'Pulled ' + stock
Pulled AAAA

not

>>> print 'Pulled', + stock
PulledTraceback (most recent call last):
  File "<ipython-input-5-7c26bb268609>", line 1, in <module>
    print 'Pulled', + stock
TypeError: bad operand type for unary +: 'str'

You're asking Python to apply the + symbol to a string like +23 makes a positive 23, and she's objecting.

DSM
  • 342,061
  • 65
  • 592
  • 494
  • 1
    thank you for the feedback, bad misstep on my part and apologies for the misdirection with this one. Appreciate your help, i spend a while looking at the wrong thing! :( – heinztomato Dec 21 '13 at 18:27
  • 2
    Another cause that is not the culprit here is the typo `str =+ 'some text'` which of course should be `str += 'some text'`. – Mark Kortink Aug 17 '19 at 20:49
16

The code works for me. (after adding missing except clause / import statements)

Did you put \ in the original code?

urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' \
              + stock + '/chartdata;type=quote;range=5d/csv'

If you omit it, it could be a cause of the exception:

>>> stock = 'GOOG'
>>> urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'
>>> + stock + '/chartdata;type=quote;range=5d/csv'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for unary +: 'str'

BTW, string(e) should be str(e).

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • thanks for your feedback falsetru, i took the \ out and am still receiving the operand error. i cant figure it out. The program works but i am afraid the operand error will cause more problems further down the line, it keeps triggering at the `if int(splitLine[0]) > int(lastUnix):` line. ill keep looking for the fix, thanks again! also, i noticed right after submitting that I literally wrote string(e), doh! – heinztomato Dec 17 '13 at 21:09
  • 1
    @heinztomato, Please update your question with the full traceback. – falsetru Dec 18 '13 at 02:06
  • sorry for the delay, here is the complete code and the response after running the program. it seems to make it to print 'Pulled' but the operand issue is returning instead of the stock, then the loop goes to the next input. any ideas? thanks again for your help. – heinztomato Dec 21 '13 at 16:43
  • @heinztomato, Remove the `try... except ...`, rerun the program and please update the question with **the full traceback**. `try ... except .., e: print(e)` does not show the full traceback. – falsetru Dec 21 '13 at 16:55
  • Adding `\ ` solved my issue. I have worked with Java more often and this is one of the pitfalls of cross language programming. Looking at the multi-line string concatenation I had, this small difference of Python syntax from Java escaped my notice. – NurShomik Nov 28 '21 at 20:23
3

I had the same error message but the cause was different. A return after tripple quotation marks was the issue.

On Python 3:

final_sentence="""Pulled
"""+stock+""".""" 
print (final_sentence)

works, but not:

final_sentence="""Pulled"""
+stock+""".""" 
print (final_sentence)
Al Martins
  • 431
  • 5
  • 13