Convert integer to string in Python
In this article, we’ll explore different methods for converting an integer to a string in Python. The most straightforward approach is using the str() function.
Using str() Function
str() function is the simplest and most commonly used method to convert an integer to a string.
n = 42
s = str(n)
print(s)
Output
42
Explanation: str(n) converts n to a string, resulting in '42'.
Using f-strings
For Python 3.6 or later, f-strings provide a quick way to format and convert values.
n = 42
s = f"{n}"
print(s)
Output
42
Explanation: The {n} inside the f-string automatically converts n to a string.
Using format() Function
format() function inserts values into {} placeholders in a string. This is similar to f-strings but works with older versions of Python (before 3.6).
n = 42
s = "{}".format(n)
print(s)
Output
42
Explanation: format() places n into {}, converting it to '42'
Using %s Keyword
The %s keyword allows us to insert an integer (or any other data type) into a string. This method is part of the older style of string formatting but still works in Python.
n = 42
s = "%s" % n
print(s)
Output
42
Explanation: The %s keyword acts as a placeholder within the string and automatically converts n to a string before inserting it in place of %s. This approach can be useful for quick formatting but is less commonly used than f-strings or format().
Using repr() for Debugging
repr() function is usually used for debugging, as it gives a detailed string version of an object. While it also converts integers to strings, it’s not the most common method for simple integer-to-string conversion.
n = 42
s = repr(n)
print(s)
Output
42
Explanation: repr(n) returns a string '42'. It’s similar to str() but usually used for debugging.
Related Articles: