Convert an integer to a Python string
This post will discuss how to convert an integer to a string in Python.
1. Using String constructor
The standard solution to convert an object to a string is using the str(object) function.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10 s = str(x) print((s, type(s))) # ('10', <class 'str'>) |
The str(object) function internally calls the __str__() function of the object, which returns the object’s string representation.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10 s = x.__str__() print((s, type(s))) # ('10', <class 'str'>) |
2. Using f-strings
Another Pythonic approach is to use the f-string (formatted string literal) starting with Python 3.6. You can do this by prefixing the string literal with f so that the replacement fields within the curly braces {} gets evaluated at the run time.
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10 s = f'{x}' print((s, type(s))) # ('10', <class 'str'>) |
3. Using str.format() function
Before version 3.6, you can use the str.format() function. Here’s an example of its usage:
|
1 2 3 4 5 6 7 |
if __name__ == '__main__': x = 10 s = '{}'.format(x) print((s, type(s))) # ('10', <class 'str'>) |
That’s all about converting an integer to a string in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)