![Int Int](/uploads/1/2/4/8/124865917/797314599.png)
I want to convert an integer to a string in Python. I am typecasting it in vain:
Python Strings - Learn Python in simple and easy steps starting from basic to advanced concepts with examples including Python Syntax Object Oriented Language, Methods, Tuples, Tools/Utilities, Exceptions Handling, Sockets, GUI, Extentions, XML Programming.
When I try to convert it to string, it's showing an error like
int
doesn't have any attribute called str
.HickHick
10 Answers
Links to the documentation:
The problem seems to come from this line:
d.str()
. Conversion to a string is done with the builtin
str()
function, which basically calls the __str__()
method of its parameter.Bastien LéonardBastien Léonard
Lasse Vågsæther KarlsenLasse Vågsæther Karlsen
There is not typecast and no type coercion in Python. You have to convert your variable in an explicit way.
To convert an object in string you use the
str()
function. It works with any object that has a method called __str__()
defined. In factis equivalent to
The same if you want to convert something to int, float, etc.
Andrea AmbuAndrea Ambu
To manage non-integer inputs:
Ok, if I take your latest code and rewrite a bit to get it working with Python:
![Int Int](/uploads/1/2/4/8/124865917/926866765.jpg)
It gives me something like:
Which is the first characters of the string result
pow(a,b)
.What are we trying to do here?niknik
maxaposteriorimaxaposteriori
SuperNovaSuperNova
NikolasNikolas
SuperNovaSuperNova
For someone who wants to convert int to string in specific digits, the below method is recommended.
For more details, you can refer to Stack Overflow question Display number with leading zeros.
GearonGearon
With the introduction of f-strings in Python 3.6, this will also work:
It is actually faster than calling
str()
, at the cost of readability.In fact, it's faster than
%x
string formatting and .format()
!Alec AlameddineAlec Alameddine
protected by Aniket ThakurApr 5 '15 at 18:15
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Would you like to answer one of these unanswered questions instead?