Python Convert String to Number

1. Introduction

When working with data in Python, you might often need to convert a string to a numeric type. This could be due to receiving numeric data in text format from user input, files, or network operations. Python provides straightforward methods to convert strings to integers or floating-point numbers, enabling further mathematical computations or data analysis. This blog post explains how to convert strings into numbers in Python.


Converting a string to a number in Python refers to the process of transforming a string that represents a numeric value (such as '123' or '3.14') into a numeric data type (int for integers, float for floating-point numbers). Python achieves this with its built-in int() and float() functions.

2. Program Steps

1. Determine whether the numeric string represents an integer or a floating-point number.

2. Use the int() function to convert an integer string to an integer.

3. Use the float() function to convert a floating-point string to a float.

4. Handle potential exceptions if the string does not represent a valid number.

3. Code Program

# Step 1: Determine the type of number and prepare strings
int_string = '42'
float_string = '3.14'

# Step 2: Convert the integer string to an integer
int_number = int(int_string)

# Step 3: Convert the floating-point string to a float
float_number = float(float_string)

# Step 4: Print the results

# Handling invalid conversions
    invalid_string = 'not_a_number'
    # This will raise a ValueError
    invalid_number = int(invalid_string)
except ValueError as e:
    print(f"Error: {e}")


Error: invalid literal for int() with base 10: 'not_a_number'


1. int_string and float_string are strings representing an integer and a floating-point number, respectively.

2. int_number is obtained by converting int_string to an integer using int().

3. Similarly, float_number is obtained by converting float_string to a float using float().

4. The print statements display the converted numeric values, verifying the successful conversion of the strings to numbers.

5. An attempt to convert invalid_string, which does not represent a valid number, results in a ValueError. This exception is caught and an error message is printed, demonstrating how to handle invalid input.