In this post, we are going to learn How to convert integer to string in Python with code examples and using simple methods. sometimes while data manipulation, we have to convert numbers to python string in this post we will learn some easy ways to achieve this in python programming.
1. Using inbuilt str() method
str() function is in built function in python that you can use to convert a number to string using these below steps.
The syntax for this function is:
str(integer_value)
- In this example, we are converting the number variable = 55.
- First, we are verifying the type of the variable by using the python type() method.
- Using the use str() function to convert integer to a python string
- Finally Verifying the type of converted number.
Let understand with example
Example : str() method to convert int to Python string
variable = 55
print(type(variable))
string_num = str(variable)
print(type(string_num))
Output
<class 'int'>
<class 'str'>
2. Using “%s” formatter keyword
Another technique that we are going to learn is “%s” formatted keyword. Let us understand this with the help of examples below:
Syntax:
“%s” % number
- In this example, we are converting the number variable = 55.
- First, we are verifying the type of the variable by using the python type() method.
- Verify the type of this variable by using type() function
- using “% s” % variable to convert to an integer to Python string
- Finally Verifying the type of converted number.
variable = 55
print(type(variable))
variable = "% s" % variable
print(type(variable))
Output
<class 'int'>
<class 'str'>
3. Using in-built .format() function
The third way, which we are going to learn is by using the format() method of Python. Let us understand this with the example below:
Syntax:
‘{}’.format(number)
If we have a number variable = 55 , we can convert it to string.
- First, we will Verify the type of this variable by using the type() function.
- Using “{}”.format(variable) We will convert an integer number to a Python string.
- Finally, we will Verify the type is changed to string using type() function.
variable = 55
print(type(variable))
variable = "{}".format(variable)
print(type(variable))
Output
<class 'int'>
<class 'str'>
4. Using in built f-string of Python
The fourth way that we are going to learn is by using the f-string in-built method of Python language.
Syntax
f'{integer}’
These are the steps we are using
- If we have a number variable = 55, we can convert it to a Python string.
- First, we will Verify the type of this variable by using the type() function
- By using f'{integer}’ in-built function to convert an integer number to Python string
- Finally Verifying the type of converted number.
variable = 55
print(type(variable))
string_num = f'{variable}'
print(type(string_num))
Output
<class 'int'>
<class 'str'>
Conclusion :
We have explored 4 different ways to convert integer to Python string with code example, We can any of them to convert an integer number to python string.