Q:

How to convert int to string in Python

belongs to collection: Python String Programs

0

We can convert an integer data type using the Python built-in str() function. This function takes any data type as an argument and converts it into a string. But we can also do it using the "%s" literal and using the .format() function. Below is the syntax of the str() function.

Syntax -

str(integer_Value)  

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Example - 1 Using the str() function

n = 25  
# check  and print type of num variable  
print(type(n))  
print(n)  
  
# convert the num into string  
con_num = str(n)  
  
# check  and print type converted_num variable  
print(type(con_num))  
print(con_num)  

 

Output:

<class 'int'>
25
<class 'str'>
25

 

Example - 2 Using the "%s" integer

n = 10  
  
# check and print type of n variable  
print(type(n))  
  
# convert the num into a string and print  
con_n = "% s" % n  
print(type(con_n))  

 

Output:

<class 'int'>
<class 'str'>

 

Example - 3: Using the .format() function

n = 10  
  
# check  and print type of num variable  
print(type(n))  
  
# convert the num into string and print  
con_n = "{}".format(n)  
print(type(con_n))  

 

Output:

<class 'int'>
<class 'str'>

 

Example - 4: Using f-string

n = 10  
  
# check  and print type of num variable  
print(type(n))  
  
# convert the num into string  
conv_n = f'{n}'  
  
# print type of converted_num  
print(type(conv_n))   

 

Output:

<class 'int'>
<class 'str'>

 

We have defined all methods of converting the integer data type to the string type. You can use one of them according to your requirement.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to concatenate two strings in Python... >>
<< How to Convert Python List to String...