Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 459
blueplastic Avatar asked Aug 15 '11 16:08

blueplastic


People also ask

How do you convert an int to a string in Python 3?

We can convert numbers to strings using the str() method. We'll pass either a number or a variable into the parentheses of the method and then that numeric value will be converted into a string value.

How do you convert an integer to a string in Python?

To convert an integer to string in Python, use the str() function. This function takes any data type and converts it into a string, including integers. Use the syntax print(str(INT)) to return the int as a str , or string.

How do you convert int to string without using library functions in Python?

Convert int to string python without str() function Simple example code keeps dividing a given int value by 10 and prepending the remainder to the output string. Use the ordinal number of '0' plus the remainder to obtain the ordinal number of the remainder, and then convert it to string using the chr function.


2 Answers

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.

like image 141
Jeremy Avatar answered Oct 12 '22 00:10

Jeremy


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

like image 14
Daniel Roseman Avatar answered Oct 12 '22 02:10

Daniel Roseman