1574

How do I convert an integer to a string?

42   ⟶   "42"

For the reverse, see How do I parse a string to a float or int?. Floats can be handled similarly, but handling the decimal points can be tricky because floating-point values are not precise. See Converting a float to a string without rounding it for more specific advice.

cottontail
  • 10,268
  • 18
  • 50
  • 51
Hick
  • 35,524
  • 46
  • 151
  • 243

14 Answers14

2328
>>> str(42)
'42'

>>> int('42')
42

Links to the documentation:

str(x) converts any object x to a string by calling x.__str__(), or repr(x) if x doesn't have a __str__() method.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Bastien Léonard
  • 60,478
  • 20
  • 78
  • 95
150

Try this:

str(i)
Lasse V. Karlsen
  • 380,855
  • 102
  • 628
  • 825
69

There is no typecast and no type coercion in Python. You have to convert your variable in an explicit way.

To convert an object into a 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.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
Andrea Ambu
  • 38,188
  • 14
  • 54
  • 77
  • this solution helped me, i was converting an alphanumeric string to a numeric string, replacing letters with their ascii values, however directly using str() function was not working, but __str__() worked. Example (python2.7); s = "14.2.2.10a2" non working code: print "".join([ str(ord(c)) if (c.isalpha()) else c for c in s ]) working code: print "".join([ ord(c).__str__() if (c.isalpha()) else c for c in s ]) Expected output: 14.2.2.10972 – Jayant May 07 '20 at 05:49
20

To manage non-integer inputs:

number = raw_input()
try:
    value = int(number)
except ValueError:
    value = 0
Georgy
  • 12,464
  • 7
  • 65
  • 73
nik
  • 13,254
  • 3
  • 41
  • 57
18
>>> 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
cacti5
  • 2,006
  • 2
  • 25
  • 33
maxaposteriori
  • 7,267
  • 4
  • 28
  • 25
14

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohamed Makkaoui
  • 393
  • 6
  • 10
  • This approach has the advantage that it can also accept floats without changing anything - although it might not handle decimal digits exactly the way you want. You can explicitly specify how to handle decimals, but then it will stop accepting an integer. – Karl Knechtel Aug 10 '22 at 02:27
13

In Python => 3.6 you can use f formatting:

>>> int_value = 10
>>> f'{int_value}'
'10'
>>>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SuperNova
  • 25,512
  • 7
  • 93
  • 64
8

The most decent way in my opinion is ``.

i = 32   -->    `i` == '32'
Nikolas
  • 161
  • 1
  • 12
  • 3
    Note that this is equivalent to `repr(i)`, so it will be weird for longs. (Try ``i = `2 ** 32`; print i``) –  May 19 '15 at 15:46
  • 20
    This has been deprecated in python 2 and completely removed in python 3, so I wouldn't suggest using it anymore. https://docs.python.org/3.0/whatsnew/3.0.html#removed-syntax – teeks99 Jul 13 '15 at 18:47
8

You can use %s or .format:

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

Or:

>>> '{}'.format(10)
'10'
>>>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SuperNova
  • 25,512
  • 7
  • 93
  • 64
7

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Eugene
  • 10,627
  • 5
  • 49
  • 67
5

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()!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alec
  • 8,529
  • 8
  • 37
  • 63
1

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'>)


Edem Robin
  • 43
  • 5
0

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]
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Code Carbonate
  • 640
  • 10
  • 18
0

You can also call format():

format(42)                 # 42 --> '42'

If you want to add a thousands separator:

num = 123456789
format(num, ",")           # '123,456,789'
f"{num:,}"
"{:,}".format(num)

or to convert to string representation of floats

format(num, ",.2f")        # '123,456,789.00'
f"{num:,.2f}"
'{:,.2f}'.format(num)

For a "European" separator:

format(num, "_.2f").replace('.', ',').replace('_', '.')   # '123.456.789,00'
f"{num:_.2f}".replace('.', ',').replace('_', '.')
"{:_.2f}".format(num).replace('.', ',').replace('_', '.')
cottontail
  • 10,268
  • 18
  • 50
  • 51