Weirdness calling str() to convert integer to string in Python 3?

58,352

Solution 1

That code alone won't give you an error. For example, I just tried this:

~ $ python3.2
>>> variable = str(21)
>>> variable
'21'

Somewhere in your code you're defining that str = something else, masking the builtin definition of str. Remove that and your code will work fine.

Solution 2

Because you've probably overwritten the str function by calling your own variable str.

Share:
58,352
blueplastic
Author by

blueplastic

Updated on April 10, 2020

Comments

  • blueplastic
    blueplastic about 4 years

    Why is this giving me an error?

    >>> variable = str(21)
    
    Traceback (most recent call last):
      File "<pyshell#101>", line 1, in <module>
        variable = str(21)
    TypeError: 'str' object is not callable
    
    • Wooble
      Wooble almost 13 years
      did you name a variable "str"?
    • mouad
      mouad almost 13 years
      Did you define another string variable and assign it to a variable str ? because doing so you end up shadowing the builtin function str() e.g: str = 'test'; print(str(124)).
    • smci
      smci about 10 years
      The downvotes are misplaced. Most of us have shadowed builtins, when learning. Look how many code examples out there with list = [...]. I updated the title of this question.
  • blueplastic
    blueplastic almost 13 years
    I think you might be right. I closed out of my IDLE session (which had a lot of earlier code samples I found online loaded), and now I can use the built-in str function properly. One of those earlier code samples must have done something quirky to the BIF str(). Thanks!