[python] Converting integer to string in Python

I want to convert an integer to a string in Python. I am typecasting it in vain:

d = 15
d.str()

When I try to convert it to string, it's showing an error like int doesn't have any attribute called str.

This question is related to python string integer

The answer is


Here is a simpler solution:

one = "1"
print(int(one))

Output console

>>> 1

In the above program, int() is used to convert the string representation of an integer.

Note: A variable in the format of string can be converted into an integer only if the variable is completely composed of numbers.

In the same way, str() is used to convert an integer to string.

number = 123567
a = []
a.append(str(number))
print(a) 

I used a list to print the output to highlight that variable (a) is a string.

Output console

>>> ["123567"]

But to understand the difference how a list stores a string and integer, view the below code first and then the output.

Code

a = "This is a string and next is an integer"
listone=[a, 23]
print(listone)

Output console

>>> ["This is a string and next is an integer", 23]

With the introduction of f-strings in Python 3.6, this will also work:

f'{10}' == '10'

It is actually faster than calling str(), at the cost of readability.

In fact, it's faster than %x string formatting and .format()!


Try this:

str(i)

If you need unary numeral system, you can convert an integer like this:

>> n = 6
>> '1' * n
'111111'

If you need a support of negative ints you can just write like that:

>> n = -6
>> '1' * n if n >= 0 else '-' + '1' * (-n)
'-111111'

Zero is special case which takes an empty string in this case, which is correct.

>> n = 0
>> '1' * n if n >= 0 else '-' + '1' * (-n)
''

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>

You can use %s or .format:

>>> "%s" % 10
'10'
>>>

Or:

>>> '{}'.format(10)
'10'
>>>

For someone who wants to convert int to string in specific digits, the below method is recommended.

month = "{0:04d}".format(localtime[1])

For more details, you can refer to Stack Overflow question Display number with leading zeros.


>>> i = 5
>>> print "Hello, world the number is " + i
TypeError: must be str, not int
>>> s = str(i)
>>> print "Hello, world the number is " + s
Hello, world the number is 5

There are several ways to convert an integer to string in python. You can use [ str(integer here) ] function, the f-string [ f'{integer here}'], the .format()function [ '{}'.format(integer here) and even the '%s'% keyword [ '%s'% integer here]. All this method can convert an integer to string.

See below example

#Examples of converting an intger to string

#Using the str() function
number = 1
convert_to_string = str(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the f-string
number = 1
convert_to_string = f'{number}'
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  {}'.format() function
number = 1
convert_to_string = '{}'.format(number)
print(type(convert_to_string)) # output (<class 'str'>)

#Using the  '% s '% keyword
number = 1
convert_to_string = '% s '% number
print(type(convert_to_string)) # output (<class 'str'>)



For Python 3.6, you can use the f-strings new feature to convert to string and it's faster compared to str() function. It is used like this:

age = 45
strAge = f'{age}'

Python provides the str() function for that reason.

digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>

For a more detailed answer, you can check this article: Converting Python Int to String and Python String to Int


To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'

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 fact

str(a)

is equivalent to

a.__str__()

The same if you want to convert something to int, float, etc.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to integer

Python: create dictionary using dict() with integer keys? How to convert datetime to integer in python Can someone explain how to append an element to an array in C programming? How to get the Power of some Integer in Swift language? python "TypeError: 'numpy.float64' object cannot be interpreted as an integer" What's the difference between integer class and numeric class in R PostgreSQL: ERROR: operator does not exist: integer = character varying C++ - how to find the length of an integer Converting binary to decimal integer output Convert floats to ints in Pandas?