1

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?

1
  • 2
    dont use str its python internal variable Commented Jul 31, 2013 at 6:38

5 Answers 5

10

Call the variable something other than str. It is shadowing the str built in function.

Sign up to request clarification or add additional context in comments.

Comments

7

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'

3 Comments

I think it's not correct. You may override built-in symbols (though not recommended of course). You can say str='abc'; print(str). The problem here is that he calls it by saying str() which is not correct, he must use []
@JohannesP you didn't understand the problem; limelights answer is correct.
@JohannesP On line 8 he wants the output to be 1%done. Changing the string name from str to number_string will output what OP is asking for even though that in it self will be incorrect and he'll face the problem you're solving to access a strings char by brackets.
2

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.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.