I have the following code
f = open('BigTestFile','w');
str = '0123456789'
for i in range(100000000):
if i % 1000000 == 0:
print(str(i / 1000000) + ' % done')
f.write(str)
f.close()
When I run it, I get this TypeError:
Traceback (most recent call last):
File "gen_big_file.py", line 8, in <module>
print(str(i / 1000000) + ' % done')
TypeError: 'str' object is not callable
Why is that? How to fix?
Call the variable something other than str.
It is shadowing the str built in function.
It's because you overrode the function str on line 3.
str() is a builtin function in Python which takes care of returning a nice string representation of an object.
Change line 3 from
str = '0123456789'
to
number_string = '0123456789'
You overwrote str which is normally a constructor for strings.
You could just change this line to "{} % done".format(i) if you really don't want to change it.
And if you insist on overwriting the str class instantiator with an actual string then replacing str(i) with "".__class__(i) would fix the error.
First of all, if you want to access the ith element of something, you need to use [i] and not (i). And second, as the others already mentioned, don't override str, the function to obtain any object's string representation.
Related
When I print a numpy.timedelta64 scalar using string formatting I get a TypeError.
In [10]: td = np.timedelta64(5410102,'us')
In [12]: td.ndim # check td is really a scalar
Out[12]: 0
In [13]: print("td: {}".format(td))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-bae2acf5773a> in <module>
----> 1 print("td: {}".format(td))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
In [14]: print("td: {!r}".format(td)) # printing using repr() works as expected
td: numpy.timedelta64(5410102,'us')
In [15]: print(td) # Just printing also works fine
5410102 microseconds
Any ideas what's going on?
Update:
The error seems to be in the numpy.timedelta64.__format__() function.
In [67]: td.__format__("")
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-67-6acc460ea008> in <module>
----> 1 td.__format__("")
TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.timedelta'
It just seems a bug to me. A work around is to convert it to string before formatting.
In [68]: print("{}".format(str(td)))
5410102 microseconds
You can read about datetime.timedelta function here. Anyways, it says that this function return an instance of a Date object.
The error appears because you can't concatenate a string with an object.
In order to solve this problem, you need to concatenate the string with a printable representation of the object using one of the follwing ways:
print(str + str(object)) # In this case, turns to the toString() function of the object, if exists (otherwise it returns an error). Converts the text the object shows to a string. In this case, it's possible to use that method on Date instances.
print(str + repr(object) # repr() functions returns a printable representation of the object of their class.
By the way, the line print(object) works because it turns to the toString() function of the object. Using print(str + object) is forbidden because it tries to print a non-concatenative variables which is not possible, as explained.
This question already has answers here:
Python: 'str' object is not callable
(5 answers)
Closed 5 years ago.
I am trying to write a small web request program to get some of the popular Instagram users (this is python 3).
final_list = [];
for idx in range(1, 5, 1):
url = "http://zymanga.com/millionplus/" + str(idx) + "f"; # idx is for page number
print(url);
headers = {...omitted header details...};
req = urllib.request.Request(url, None, headers);
with urllib.request.urlopen(req) as f:
str = f.read().decode('utf-8');
initial_list = re.findall(r'target=\"_blank\">([^<]+?)</a>,', str);
for item in initial_list:
final_list.append(item);
The first iteration works well (and I am able to get the users on the first page), however on the second iteration, I am encounting the following error:
Traceback (most recent call last):
File ".\web_search.py", line 8, in <module>
url = "http://zymanga.com/millionplus/" + str(idx) + "f";
TypeError: 'str' object is not callable
Could you please let me know what might caused the problem, tried to debug but couldn't resolved it. Thanks!
You've redefined str within your loop so that it refers to the variable read from the response. Choose a different name.
str = f.read().decode('utf-8')
str is the contents of the file you read on the last pass through the loop. You are trying to call it like a function with str(idx) but it is not one.
Don't use the names of built-in functions for your own variables.
You are using str as a variable at str = f.read().decode('utf-8');. In the next loop, the str(idx) is no longer the class str but the value from f.read().decode('utf-8').
Never use the class types as variable names. Just to illustrate the mistake:
>>> str
<class 'str'>
>>> str(1)
'1'
>>> str = 'some string'
>>> str
'some string'
>>> str(1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
I keep receiving this error when I try to run this code for the line "encoded.append("i")":
AttributeError: 'str' object has no attribute 'append'
I cannot work out why the list won't append with the string. I'm sure the problem is very simple Thank you for your help.
def encode(code, msg):
'''Encrypts a message, msg, using the substitutions defined in the
dictionary, code'''
msg = list(msg)
encoded = []
for i in msg:
if i in code.keys():
i = code[i]
encoded.append(i)
else:
encoded.append(i)
encoded = ''.join(encoded)
return encoded
You set encoded to string here:
encoded = ''.join(encoded)
And of course it doesn't have attribute 'append'.
Since you're doing it on one of cycle iteration, on next iteration you have str instead of list...
>>> encoded =["d","4"]
>>> encoded="".join(encoded)
>>> print (type(encoded))
<class 'str'> #It's not a list anymore, you converted it to string.
>>> encoded =["d","4",4] # 4 here as integer
>>> encoded="".join(encoded)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
encoded="".join(encoded)
TypeError: sequence item 2: expected str instance, int found
>>>
As you see, your list is converted to a string in here "".join(encoded). And append is a method of lists, not strings. That's why you got that error. Also as you see if your encoded list has an element as integer, you will see TypeError because, you can't use join method on integers. Better you check your all codes again.
Your string conversion line is under the else clause. Take it out from under the conditional, and the for loop so that it's the last thing done to encoded. As it stands, you are converting to a string halfway through your for loop:
def encode(code, msg):
'''Encrypts a message, msg, using the substitutions defined in the
dictionary, code'''
msg = list(msg)
encoded = []
for i in msg:
if i in code.keys():
i = code[i]
encoded.append(i)
else:
encoded.append(i)
# after all appends and outside for loop
encoded = ''.join(encoded)
return encoded
You are getting the error because of the second expression in you else statement.
''.join(encoded) returns a string that gets assigned to encoded
Thus encoded is now of type string.
In the second loop you have the .append(i) method in either if/else statements which can only be applied to lists and not strings.
Your .join() method should appear after the for loop right before you return it.
I apoligise if the above text does not appear right. This is my first post and I still trying to figure out how this works.
I'm creating a function that consolidates a couple of lists into a string and am encountering the below error.
Traceback (most recent call last):
File "TraditionalRoute\BioKeywords.py", line 65, in <module>
print(PrintKeyDefs())
File "TraditionalRoute\BioKeywords.py", line 30, in PrintKeyDefs
defsTwo = dict(map(None, letters, defsOne))
TypeError: 'NoneType' object is not callable
My code is as follows:
# print keyword and three definitions, one of which is the correct definition
def PrintKeyDefs():
print('\nRandomly selected keyword:',SelectKeyword(),'\n')
# definitions below
defsOne = []
defsOne.append(keywords[ChosenKeyword]) # choosing the keyword
RandDefCount = 0
while RandDefCount < 2: # adding two random keywords to the list
defsOne.append(keywords[random.choice(words)])
RandDefCount += 1
random.shuffle(defsOne) # randomizing the keywords
letters = ['A) ','B) ','C) ']
defsTwo = dict(map(None, letters, defsOne)) # trying to put them together in a dict. the problem is here
defsThree = ''
defsThree += '\n'.join(defsTwo) # changing to a string
return defsThree
Would anyone be able to suggest a possible fix as I've spent quite a while on this and haven't figured it out yet. Thanks.
EDIT: Forgot to mention I'm using Python 3
If you are using Python 2, then either map or dict is bound to None. Check the rest of your code for assignments to either name.
Note that instead of map(None, iterable1, iterable2) you can use zip(iterable1, iterable2) to get the same output.
If you are using Python 3, then the map() method does not support None as a first argument:
>>> list(map(None, [1], [2]))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable
and you certainly want to use zip() there:
defsTwo = dict(zip(letters, defsOne))
If you're using Python 3 then first argument to map is ought to be a function. You're passing None so it tries to call a None. This is a different than in Python 2, when None was treated like an identity function (Python's 2 map).
For Python 2 case see Martijn Pieters's answer.
#Use Of Zip() function
#Generate tuple
x=zip( range(5), range(1,20,2) )
print("Tuple : ",tuple(x))
#Generate List
x=zip( range(5), range(1,20,2) )
print("List : ",list(x))
#Generate dictonary
x=zip( range(5), range(1,20,2) )
print("Dictonary : ",dict(x))
I am having a weird issue with Python. For some reason, when I call it from the command line, I can use the replace() function as much as I want but I cannot use it inside a specific class. The code yields the following (well-known) error:
File "/homes/mmj11/malice/lexer.py", line 96, in replaceInTree
tree[i] = tree[i].replace(" "," ")
TypeError: 'str' object is not callable
The function I'm using is the following:
def replaceInTree(self, tree):
for i in range(len(tree)):
if type(tree[i] is str):
tree[i] = tree[i].replace(" "," ")
tree[i] = tree[i].replace(tree[i], self.getToken(tree[i]))
else:
tree[i] = self.replaceInTree(tree)
return tree
I really think this should not happen as I can do the exact same thing in the command line. I am very sure that str's are meant to be callable.
Instead of
if type(tree[i] is str):
Dont you mean to do
if type(tree[i]) is str:
I would do this:
if type(tree[i]) is str:
instead of this:
if type(tree[i] is str):
The way you have it written evaluates to if type(false), which is equivalent to if bool, which will always be truthy.