Number-String Conversion in Python

This page demonstrates how to convert numbers to strings and strings to numbers using Python.

Convert Number to String

Here’s a Python script for converting a number to a string:

# This python script dictates number to string conversion
num1 = 12345
conv_num1 = str(num1)
print("Input type is ",type(num1),"& Number IN is",num1)
print("Output type is ",type(conv_num1),"& string OUT is",conv_num1)

Explanation:

  • We start with a number, num1, which is an integer in this case.
  • The str() function is used to convert the number to its string representation. The result is stored in conv_num1.
  • The print() statements then display the original number and its data type, as well as the converted string and its data type, confirming the conversion.

Output:


Input type is <class 'int'> & Number IN is 12345
Output type is <class 'str'> & string OUT is 12345

Convert String to Number

Here’s a Python script for converting a string to a number:

# This python script dictates string to number conversion
num2 = '500'
conv_num2 = int(num2)
print("Input type is ",type(num2),"& string IN is",num2)
print("Output type is ",type(conv_num2),"& number OUT is",conv_num2)

Explanation:

  • We begin with a string, num2, which contains a numerical value.
  • The int() function attempts to parse the string and convert it into an integer. The resulting integer is assigned to conv_num2.
  • The print() statements show the original string and its type, followed by the converted integer and its type, proving the conversion.

Output:

Input type is  <class 'str'> & string IN is 500
Output type is  <class 'int'> & number OUT is 500