You may use the Python int and float functions for converting a string to an integer and float numbers before doing any operation, as shown in the examples below. Using int function for converting a string into integer. Using the same code as in above example, except converting the string value into an integer by using int.
I want to convert an integer to a string in Python. I am typecasting it in vain:
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:
![List List](/uploads/1/2/5/0/125060828/323729734.jpg)
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:
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?