Using format() Function
The `format()` function is another way to convert an integer to a string in Python. It allows you to create a formatted string by replacing placeholders with corresponding values.
To use the `format()` function, you define a string with placeholders using curly braces `{}` & then call the `format()` function on that string, passing the values you want to substitute.
For example:
score = 95
message = "Your score is {}".format(score)
print(message)

You can also try this code with Online Python Compiler
Run Code
Output:
Your score is 95
In this code, the placeholder `{}` inside the string acts as a position where the value of `score` will be inserted. The `format()` function is called on the string, & the `score` variable is passed as an argument. Python converts the integer `score` to a string & replaces the placeholder with the corresponding value.
You can also use multiple placeholders & pass multiple values to the `format()` function:
x = 10
y = 20
result = "The sum of {} and {} is {}".format(x, y, x + y)
print(result)

You can also try this code with Online Python Compiler
Run Code
Output:
The sum of 10 and 20 is 30

You can also try this code with Online Python Compiler
Run Code
In this example, the string contains three placeholders `{}`, & the `format()` function is called with three arguments: `x`, `y`, & the expression `x + y`. Python evaluates the expression & replaces the placeholders with the corresponding values.
Note: The `format()` function provides additional formatting options, such as specifying the width, alignment, and precision of the substituted values.
Using repr() for Debugging
The `repr()` function is mainly used for debugging purposes, but it can also convert an integer to a string. The `repr()` function returns a string representation of an object suitable for debugging.
For example:
num = 42
string_num = repr(num)
print(string_num) # Output: '42'
print(type(string_num))

You can also try this code with Online Python Compiler
Run Code
Output:
<class 'str'>
In this code, we pass the integer `num` to the `repr()` function, which returns a string representation of the integer. The resulting string `string_num` is then printed, showing the value `'42'`. We also print the type of `string_num` using the `type()` function, confirming that it is indeed a string.
The `repr()` function is particularly useful when you want to print the string representation of an object for debugging or logging purposes. It provides a clear and unambiguous representation of the object.
Note: It's important to remember that the primary purpose of `repr()` is debugging, not necessarily formatting output for end-users. For user-friendly output, you might want to use other methods like `str()` or string formatting techniques.
Convert Int To String In Python Using %s Keyword (Positional Formatting)
Python's string formatting using the `%` operator is an older technique, but it's still widely used. The `%s` keyword is a placeholder that can be used to convert an integer to a string within a formatted string.
For example:
count = 5
message = "There are %s items in the basket." % count
print(message)

You can also try this code with Online Python Compiler
Run Code
Output:
There are 5 items in the basket.
In this code, the `%s` placeholder is used within the string to indicate where the value of `count` should be inserted. The `%` operator is then used to perform the string formatting, with `count` being passed as an argument.
You can also use multiple `%s` placeholders and pass multiple values:
x = 10
y = 20
result = "The product of %s and %s is %s." % (x, y, x * y)
print(result)

You can also try this code with Online Python Compiler
Run Code
Output:
The product of 10 and 20 is 200.
In this example, the string contains three `%s` placeholders, and the values of `x`, `y`, and the expression `x * y` are passed as a tuple using parentheses `()` after the `%` operator.
Note: While this method is still functional, it has some limitations compared to newer string formatting techniques like f-strings or the `format()` function. It can be less readable and more verbose, especially when dealing with multiple placeholders and values.
Convert Int To String In Python Using __str__() Method
In Python, you can define a special method called `__str__()` in your own classes to specify how an object should be represented as a string. This method is automatically called when you use the `str()` function on an instance of your class
For example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old."
person = Person("Priya", 21)
print(str(person))

You can also try this code with Online Python Compiler
Run Code
Output:
Priya is 21 years old.
In this code, we define a `Person` class with an `__init__()` method to initialize the `name` and `age` attributes. We also define the `__str__()` method, which returns a string representation of the `Person` object.
When we create an instance of the `Person` class and pass it to the `str()` function, Python automatically calls the `__str__()` method to obtain the string representation of the object.
When it could be used: The `__str__()` method is useful when you want to provide a custom string representation for your objects, especially when working with user-defined classes.
Convert Int To String In Python Using chr() Function
The `chr()` function in Python is used to convert an integer representing a Unicode code point to its corresponding character. While it's not commonly used for converting integers to strings in general, it can be used in specific cases where you want to convert an integer to its corresponding ASCII or Unicode character.
For example:
ascii_code = 65
character = chr(ascii_code)
print(character)

You can also try this code with Online Python Compiler
Run Code
Output:
A

You can also try this code with Online Python Compiler
Run Code
In this code, the integer `65` represents the ASCII code for the character 'A'. By passing `65` to the `chr()` function, it returns the corresponding character 'A'.
The `chr()` function can handle Unicode code points as well
unicode_code = 128516
emoji = chr(unicode_code)
print(emoji)

You can also try this code with Online Python Compiler
Run Code
Output:
😄

You can also try this code with Online Python Compiler
Run Code
In this example, the integer `128516` represents the Unicode code point for the emoji '😄'. By passing `128516` to the `chr()` function, it returns the corresponding emoji character.
Note: Always remember that the `chr()` function is not commonly used for converting integers to strings in most scenarios. It is mainly used when working with ASCII or Unicode characters and their corresponding code points.
Example of Int to String Conversion in Python
Let's look at a few more example that shows converting an integer to a string in Python using different methods:
# Example 1: Using str() function
age = 25
print("My age is " + str(age))

You can also try this code with Online Python Compiler
Run Code
Output:
My age is 25
# Example 2: Using f-strings
score = 95
print(f"You scored {score} points.")

You can also try this code with Online Python Compiler
Run Code
Output:
You scored 95 points.
# Example 3: Using format() function
x = 10
y = 20
print("The sum of {} and {} is {}".format(x, y, x + y))

You can also try this code with Online Python Compiler
Run Code
Output:
The sum of 10 and 20 is 30
# Example 4: Using %s placeholder
count = 5
print("There are %s apples in the basket." % count)

You can also try this code with Online Python Compiler
Run Code
Output:
There are 5 apples in the basket.
# Example 5: Using __str__() method
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __str__(self):
return f"{self.name} is in grade {self.grade}."
student = Student("Rohan", 7)
print(str(student))

You can also try this code with Online Python Compiler
Run Code
Output:
Rohan is in grade 7
In these examples, we showed various ways to convert integers to strings:
1. Using the `str()` function to convert the integer `age` to a string explicitly.
2. Using f-strings to embed the integer `score` within a string.
3. Using the `format()` function to replace placeholders with the values of `x`, `y`, and the expression `x + y`.
4. Using the `%s` placeholder and the `%` operator to insert the integer `count` into a string.
5. Defining a custom `__str__()` method in the `Student` class to provide a string representation of the object.
Frequently Asked Questions
What is the most concise way to convert an integer to a string in Python?
Using the str() function is the most concise way to convert an integer to a string in Python.
Can I use f-strings to include expressions within a string?
Yes, f-strings allow you to embed expressions and function calls directly inside the string.
Is the %s placeholder still used for string formatting in Python?
While the %s placeholder is still functional, it has limitations compared to newer string formatting techniques like f-strings or the format() function.
Conclusion
In this article, we discussed various methods to convert an integer to a string in Python. We learned about using the str() function, f-strings, the format() function, the %s placeholder, the __str__() method, and the chr() function. Each method has its own use cases and advantages.