Converting an integer to a string in Python means taking an integer value and representing it as a string of characters so that it can be used in string-based operations such as concatenation or printing. This tutorial explains the different ways to convert int to string in Python.
- Using
str()
function. - Using
format()
function. - Using
f-strings
feature (available in Python 3.6 and above). - Using
%
operator (also known as the "string formatting operator").
Using str()
function
To convert an integer to a string in Python, the str()
function can be used. This function takes an integer as an argument and returns the corresponding string representation of the integer. Here is an example of how to use the str()
function to convert an integer to a string in Python:
Example Program:
# Convert an integer to a string
n = 15
s = str(n)
print(s) # Output: "15"
Using format()
function
The format()
function of strings can convert integers to strings. This function allows the value of a variable to be inserted into a string, and it automatically converts the variable to a string if it is not already one. Here is an example of how to convert an integer to a string in Python using the format()
method:
Example Program:
# Convert an integer to a string using the format() method
n = 10
s = "The value is {}".format(n)
print(s) # Output: "The value is 10"
Using f-strings
Feature
To convert an integer to a string using f-strings
in Python, the f
prefix can be followed by a string literal that includes the integer value inside curly braces {}
.
Example Program:
n = 24
s = f"{n}"
print(s) # Output: "24"
Using %
operator
To convert an integer to a string using the %
operator in Python, the %d
format specifier can be used, followed by the integer value. The %d
specifier indicates that the value being formatted is a decimal integer.
Example Program:
n = 30
s = "%d" % n
print(s) # Output: "30"
Instead of %d
, the %s
format specifier can also be used, which tells Python to treat the formatted value as a string.
Note that both of these methods work for any type of object, not just integers. You can use them to convert any object to a string as long as it has a string representation.