# How do I convert a number to a string in Python?

To convert a number to a string, there are various ways. Let’s see them one by one.

## Convert a number to a string using format()

### Example

In this example, we will convert a number to a string using the format() method −

# Integer to be converted
n = 60

# Display the integer and it's type
print("Integer = ",n)
print("Type= ", type(n))

# Convert the integer to string and display the type
myStr = "{}".format(n)
print("\nString = ", myStr)
print("Type = ", type(myStr))


### Output

Integer =  60
Type=  <class 'int'>
String =  60
Type =  <class 'str'>


## Convert a number to a string using str()

### Example

In this example, we will convert a number to a string using the str() method −

# Integer to be converted
n = 25

# Display the integer and it's type
print("Integer = ",n)
print("Type= ", type(n))

# Convert the integer to string using str() and display the type
myStr = str(n)
print("\nString = ", myStr)
print("Type = ", type(myStr))


### Output

Integer =  25
Type=  <class 'int'>

String =  25
Type =  <class 'str'>


## Convert a number to a string using %s format

### Example

In this example, we will convert a number to a string using the %s format specifier −

# Integer to be converted
n = 90

# Display the integer and it's type
print("Integer = ",n)
print("Type= ", type(n))

# Convert the integer to string using %s and display the type
myStr = "% s" % n
print("\nString = ", myStr)
print("Type = ", type(myStr))


### Output

Integer =  90
Type=  <class 'int'>

String =  90
Type =  <class 'str'>


## Convert a number to a string using __str__()

### Example

In this example, we will convert a number to a string using the __string__() method in Python −

# Integer to be converted
n = 150

# Display the integer and it's type
print("Integer = ",n)
print("Type= ", type(n))

# Convert the integer to string using __str__() and display the type
myStr = n.__str__()
print("\nString = ", myStr)
print("Type = ", type(myStr))


### Output

Integer =  150
Type=  <class 'int'>

String =  150
Type =  <class 'str'>


## Convert a number to a string using f-string

### Example

In this example, we will convert a number to a string using the f-string −

# Integer to be converted
n = 21

# Display the integer and it's type
print("Integer = ",n)
print("Type= ", type(n))

# Convert the integer to string using f-string and display the type
myStr = f'{n}'
print("\nString = ", myStr)
print("Type = ", type(myStr))


### Output

Integer =  21
Type=  <class 'int'>

String =  21
Type =  <class 'str'>


Advertisements