TypeError when retrieving random digits
I am trying to generate a random three digit extension:
>>> ''.join(str(x) for x in random.sample(range(1,10),3))
It works in the prompt. However, when I run the program, it raises a TypeError: str object is not callable
. This is the line that I have:
filename = hashlib.md5(imagefile.getvalue()).hexdigest() +
''.join(str(x) for x in random.sample(range(1,10),3)) + '_thumb' + '.jpg'
What am I doing wrong here and how would I fix it?
Thank you for the help. I had invoked str previously in the code, which was causing the error:
str=""
for c in i开发者_Python百科.chunks():
str += c
...
You have replaced the global name str
, which normally refers to the string type, with something else (most likely, a variable containing a string of little importance). Python does not generally treat these sorts of things as keywords (in Python 3.x, True
and False
have become keywords, where they were just global variables before).
That said, random.sample
chooses non-repeating values, which doesn't seem like a requirement for the problem of "generate a random three digit extension". Neither does avoiding zeroes. I would just pick a single random number from 0-999 inclusive and format it appropriately ('%03d', or the equivalent in the new formatting).
I've tried it out both in the console and calling it in a .py file and both work.
Are you sure you're not declaring a variable called "str" somewhere in your code before that invocation?
This works:
import random
filename= ''.join(str(x) for x in random.sample(range(1,10),3))
print filename
This:
import random
str = ''
filename= ''.join(str(x) for x in random.sample(range(1,10),3))
print filename
Give the same error you're reporting.
I would break up the statement into smaller pieces:
val=imagefile.getvalue()
m=hashlib.md5(val)
sample=random.sample(range(1,10),3)
r=''.join(str(x) for x in sample)
filename = '{m}{r}_thumb.jpg'.format(m=m.hexdigest(),r=r)
so that the traceback message will indicate which part is raising the exception. A temporary print statement or use of a debugger will then narrow down problem further.
PS. Just a guess but the error would make sense if random.sample
had been set to equal a str
.
In [62]: random.sample='1'
In [63]: random.sample(range(1,10),3)
TypeError: 'str' object is not callable
精彩评论