Given an integer, the task is to convert it into a string. This is useful when working with text formatting, concatenation or displaying numeric values as strings. For Example:
Input: n = 42
Output: '42'
Let’s explore different methods to convert an integer to a string.
Using str() Function
str() function converts a value into its string representation. It takes the integer as input and returns the equivalent string.
n = 42
s = str(n)
print(s)
print(type(s))
Output
42 <class 'str'>
Explanation: str(n) converts the integer 42 into the string '42' and type(s) confirms that the result is of type str.
Using f-strings
f-strings allow values to be placed directly inside strings using {}. Python automatically converts the integer into a string.
n = 42
s = f"{n}"
print(s)
print(type(s))
Output
42 <class 'str'>
Explanation: {n} inserts the value of n into the string and the integer is automatically converted to a string.
Using format() Function
format() function inserts values into placeholders {} inside a string.
n = 42
s = "{}".format(n)
print(s)
print(type(s))
Output
42 <class 'str'>
Explanation: format() places the integer inside the string placeholder {} and the returned value is a string.
Using %s Formatting
%s placeholder inserts values into a string and automatically converts them to string format.
n = 42
s = "%s" % n
print(s)
print(type(s))
Output
42 <class 'str'>
Explanation: %s acts as a placeholder for the value and Python converts the integer into a string before inserting it.