Convert integer to string in Python
In Python an integer can be converted into a string using the built-in str() function. The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function.
Below is the list of possible ways to convert an integer to string in python:
1. Using str() function
Syntax: str(integer_value)
Example:
Python3
num = 10# check and print type of num variableprint("Type of variable before conversion : ", type(num))# convert the num into stringconverted_num = str(num)# check and print type converted_num variableprint("Type After conversion : ",type(converted_num)) |
Output:
Type of variable before conversion : <class 'int'> Type After conversion : <class 'str'>
2. Using “%s” keyword
Syntax: “%s” % integer
Example:
Python3
num = 10# check and print type of num variableprint("Type of variable before conversion : ", type(num))# convert the num into string and printconverted_num = "% s" % numprint("Type after conversion : ", type(converted_num)) |
Output:
Type of variable before conversion : <class 'int'> Type after conversion : <class 'str'>
3. Using .format() function
Syntax: ‘{}’.format(integer)
Example:
Python3
num = 10# check and print type of num variableprint("Type before conversion : ", type(num))# convert the num into string and printconverted_num = "{}".format(num)print("Type after conversion :",type(converted_num)) |
Output:
Type before conversion : <class 'int'> Type after conversion : <class 'str'>
4. Using f-string
Syntax: f'{integer}’
Example:
Python3
num = 10# check and print type of num variableprint("Type before conversion : ",type(num))# convert the num into stringconverted_num = f'{num}'# print type of converted_numprint("Type after conversion : ", type(converted_num)) |
Output:
Type before conversion : <class 'int'> Type after conversion : <class 'str'>
5. Using __str__() method
Syntax: Integer.__str__()
Python3
num = 10# check and print type of num variableprint("Type before conversion : ",type(num))# convert the num into stringconverted_num = num.__str__()# print type of converted_numprint("Type after conversion : ", type(converted_num)) |
Output:
Type before conversion : <class 'int'> Type after conversion : <class 'str'>
6. Using str.isdigit()
Python3
str_value = "1234"if str_value.isdigit(): int_value = int(str_value) print(int_value) print(type(int_value))else: raise ValueError("Invalid literal for int(): {}".format(str_value)) |
1234 <class 'int'>






Please Login to comment...