Reputation: 1082
I wrote a Python script that goes online, fetches a page, parses the page, locates a string of numbers (e.g, 5678), and stores it in num. Now, I need to perform some mathematical functions over this num. Why can't I do that?
Grabbed a line from page: The number is '6678'. Hence, line = "The number is '6678'"
c = ""
num = ''.join(c for c in line if c.isdigit())
int(num)
print num
try=(num*2)
print try
Error:
File "script", line 20
try=(num*2)
^
SyntaxError: invalid syntax
Edit: Changed the 'try' to 't'. Silly mistake! But, now I have a new error trying to do maths with 'num', further code:
new = (((num*3)+3)-1000)
print new
Error:
Traceback (most recent call last): File "602", line 22, in new = (((num*3)+2)-250) TypeError: coercing to Unicode: need string or buffer, int found
Upvotes: 0
Views: 87
Reputation: 3682
This is a mock example. If you are using beautiful soup to return the html content of a page you would need you split the read content. You want to create a list of words not characters so you don't run into the whole 1 vs 12 issue @Jon Clements brought up.
my_list = []
for word in data.split(" "):
if word.isdigit():
my_list.append(word)
my_list = [int(i) for i in my_list]
print sum(my_list) * 2
Also, this is how try works:
try:
pass #try to do some action
except:
pass #if that action fails report
Upvotes: 1
Reputation: 466
This error occurres because you're trying to use a variable named "try", which is a python's keyword. In addition, you didn't saved the integer value of the number. Finally, your code should looks like this:
line = "4567"
num = ''.join(c for c in line if c.isdigit())
int_num = int(num)
print int_num
try1=(int_num*2)
print try1
Upvotes: 1
Reputation: 16711
You need to actually reassign the casted number:
num = int(num) # num is a string right now
Upvotes: 1