In Python, you can convert an integer to a string using the following methods:
1. Using str() Function
The simplest and most common way:
python
num = 123
string_num = str(num)
print(string_num) # Output: “123”
print(type(string_num)) # Output: <class ‘str’>
2. Using f-string (Formatted String Literals)
Introduced in Python 3.6, f-strings provide a clean way to format strings:
python
num = 123
string_num = f”{num}”
print(string_num) # Output: “123”
3. Using format() Method
Another string formatting approach:
python
num = 123
string_num = “{}”.format(num)
print(string_num) # Output: “123”
4. Using repr()
The repr() function returns a string representation of an object, suitable for debugging:
python
num = 123
string_num = repr(num)
print(string_num) # Output: “123”
Best Practice
– Use str() for straightforward conversions.
– Use f-strings or format() for embedding integers in larger strings or more complex formatting