convert int to string in python

How to Convert Integer to String in Python

Python makes it easy to convert one data type into another. Sometimes you may need to convert integer to string in Python. There are multiple ways to cast integer as string in Python using str function, %s format specifier, format function and f-strings. In this article, we will look at each of these ways in detail.


How to Convert Integer to String in Python

Here are the four different ways to convert integer to string in Python.


1. Using str

str function allows you to convert integer as well as other data types into strings in python. It is the simplest and most common way to cast an int as string. Here is the syntax for str function

str(integer)

Here is an example

>>> a = 10
>>> type(a) # print data type of int variable
>>> 'int'
>>> b= str(a) #convert int to string variable
>>> b
>>> '10'
>>> type(b) # display data type of string variable
>>> 'str'

Notice how the string variable b’s value contains single quotes when printed on line 6 above, and also its type is ‘str’

Also read : How to Increase Max File Upload Size in PHP


2. Using %s format specifier

Next, we look at how to convert integer to string using format specifier. Here is the syntax for it

"%s" % integer

Here is an example

>>> a = 10
>>> type(a) # print data type of int variable
>>> 'int'
>>> b= "%s" % a #convert int to string variable
>>> b
>>> '10'
>>> type(b) # display data type of string variable
>>> 'str'

Also read : How to Count Unique IPs & Request per IP in NGINX


3. Using format function

You can also use format function to convert int to string. Here is the syntax for format function.

'{}'.format(integer)

Here is an example

>>> a = 10
>>> type(a) # print data type of int variable
>>> 'int'
>>> b= '{}'.format(a) #convert int to string variable
>>> b
>>> '10'
>>> type(b) # display data type of string variable
>>> 'str'

Also read : How to Host Multiple Domains in One Server in NGINX


4. Using f-string

You can also use f-strings to convert into to strings in Python. Here is the syntax for it.

f'{integer}'

Here is an example

>>> a = 10
>>> type(a) # print data type of int variable
>>> 'int'
>>> b= f'{a}' #convert int to string variable
>>> b
>>> '10'
>>> type(b) # display data type of string variable
>>> 'str'

Also read : How to Set Samesite Cookies in Apache


In this article, we have described four different ways to convert int to string in Python. The most common way to do so is using str function. You may use other ways to cast int to string, depending on your requirements.

Also read : How to Convert String to UTF-8 in Python


Leave a Reply

Your email address will not be published. Required fields are marked *