How To Convert String To Number In Python

Converting from one data type to another data type is known as type conversion. In Python, there are two ways to do the conversion, Implicit and Explicit. In implicit type conversion, it takes place during compilation or runtime. It is also known as automatic type conversion which a Python interpreter performs.

In explicit type conversion, inbuilt functions are used by the user or programmer. It is also called type casting or manual conversion.

As we know that strings are a sequence of characters that are enclosed within single or double quotes. (‘ ’ or “ ”). Also, they are immutable, so we can’t change them once they are declared.

Why is there a need to convert strings to numbers in Python

There are some reasons for conversion of one data type to another data type:

  • Arithmetic calculations:  Some arithmetic calculations like addition, subtraction, multiplication and division need to be performed on strings; this time you must convert them from strings to numeric types.
  • Data analysis: If you’re working with data which contains numeric values stored as strings, you must convert them to numeric values for statistical analysis, charting, drawing, and visual information work.
  • User input:If our program accepts user input in the program, you must convert the input from a string to a numeric-format  type to validate the input or perform calculations based on the input.
  • Database operations: If our program is using a database, you may require to convert string format to numeric format before performing database operations, such as sorting or searching.

Ways to convert string to number in Python

There are several approaches to converting strings to numbers in Python.

  1. Using the int()  function
  2. Using the float() function
  3. Using the complex() function
  4. Using the eval() function
  5. Using type casting

Approach 1: Using the int()  function

This method converts a simple string into an integer using the int method within the program.

Code:

mystring = "456"
my_int = int(mystring)
print(my_int)

Output:

456

Code  Explanation:

  1. In this example, first, we declare the string value that would be converted into a number value.
  2. After this use of int() function converts into int value and is stored into a new variable.
  3. Finally, after executing the program, we can observe the desired output.

Approach 2: Using the float()  function

This method converts string values to floating point numbers using the float function. This function is more flexible than int() function. Since it can parse and convert both floats and integers.

Code:

mystring = "5.123"
my_float = float(mystring)
print(my_float)

Output:

5.123

Code Explanation:

  1. In this example, we declare string value that would be converted into floating point value.
  2. After this statement use the float function.
  3. Finally, after executing the program, we can observe the desired output.

Approach 3: Using the complex()  function

In this approach, converting string literals to complex numbers using the complex() function. To do so, the string must follow specific formatting. Particularly, it must be formatted without white spaces around the + and – operators.

Here is an example of string to complex numbers.

Code:

a = "2+3j"
b= "3+4j"
c=complex(a)+complex(b)
print(c)

Output:

(5+7j)

Code Explanation:

  1. In this program, we declare two variables that store string values.
  2. After that, create a new variable c that stores the result and applies the complex() function for converting string to complex values.
  3. After execution of the program, we get desired output.

Approach 4: Using the eval()  function

This function evaluates the string against the Python expression and returns the desired output. Using the eval() function we can convert a string to any kind of numeric type, such as  integers, floats, and complex numbers.

Code:

mystring = "1+4j"
my_complex = eval(mystring)
print(my_complex)

Output:

(1+4j)


Code Explanation:

  1. In this program, first we declare a variable that stores a string.
  2. After that, using the eval() function which converts into complex numbers.
  3. After the execution of the program, we get the required output.

Approach 5: Using the type casting

By casting method, conversion from string to any type of numeric type is possible.

Here is an example of typecasting.

Code:

my_string="12345"
my_int = int(my_string)
my_float = float(my_string)
print(my_int)
print(my_float)

Output:

12345
12345.0

Code Explanation:

  1. In the above code, firstly we declare one variable that stores string value that we would like to convert into a numeric value.
  2. After that statement, will use the float method and int method for converting into numeric values.
  3. After execution of the code, we get our desired output.

Best approaches for converting a string into a number:

As per the specific requirement in the program, the best way is inbuilt functions available for conversion of string into the numeric type in Python. The following points show the functionality of it.

Performance: Using type casting or built-in conversion functions such as int(), and float() are usually faster than the eval() function.

Input format: If the input format of the string is known, you can use specific conversion functions or methods that work best with that format. Example of a string that represents a binary number, so it can use an int() function with a base of 2.

Appropriate function: According to desired output use appropriate in-built functions like int(), float(), and complex().

Sample Problems for Converting String to Number in Python

Sample Problem 1:

Suppose we have a list of strings which  represents numeric values, such as “123”, “456”, and “789” and here we want to convert from  these strings to numbers also, calculate its sum of those integers.

Solution:

  1. Loop will perform in each string and it converts into the numeric using the inbuilt function.
  2. We then add the integer to the total sum.
  3. Finally, we print the total sum of integers.

Code:

my_list = ["123", "456", "789"]
total = 0

# loop through each string in the list
for my_string in my_list:

    total += int(my_string)

print(total)  

Output:

1368

Sample Problem 2:

Suppose we have a  list of strings which represents floating numeric values, such as “12.3”, “4.56”, and “7.89”. You want to convert these strings to floats and find the sum of all the floats in the list.

Solution:

  1. In this example, firstly we declare a list of strings that represents floating numbers.
  2. Loop will perform in each string and it converts into the numeric using the in-built float() function.
  3. We then add the floating point numbers to the total sum.
  4. Finally, we print the total sum of all floats.

Code:

my_list = ["12.3", "4.56", "7.89"]
total = 0

# loop through each string in the list
for my_string in my_list:
    # convert the string to an floating numbers using float() and add it to the total
    total += float(my_string)

print(total) 

Output:

24.75

Sample Problem 3:

You have a string that represents a complex number in the form “7+5j”. You want to convert this string to a complex number and perform arithmetic operations on it.

Solution:

  1. In this solution, we have a string “7+5j” that represents a complex number.
  2. Use of complex() function in this solution for conversion from string to complex number and store the result in a variable called my_complex.
  3. We can then perform arithmetic operations on the complex number, such as adding it to another complex number (2+3j).
  4. Finally we get desired output.

Code:

string1 = "7+5j"
my_complex = complex(string1)

# perform arithmetic operations on the complex number
result = my_complex + (2+3j)
print(result) 

Output:

(9+8j)

Sample Problem 4:

If we  have a string which  represents a numerical expression, like “3 – 4 * 5”. You want to evaluate this expression and get the result as a number.

Solution:

  1. In this solution, we have a string “3 – 4 * 5” that represents a mathematical expression.
  2. Use of  built-in eval() function  which  evaluates the expression and store the new result in a variable called the result.
  3. In this solution,the eval() function takes a string as input and calculates  it as a Python expression.
  4.  In this problem, the expression “3 – 4 * 5” is evaluated as (3 – (4 * 5)) = -17.
  5. Finally we get the desired result.

Code:

my_string = "3 - 4 * 5"
result = eval(my_string)
print(result) 

Output:

-17

Sample Problem 5:

If we have given  a string which  represents a numeric value, such as “456”. You want to convert this string to an integer using type casting.

Solution:

  1. In this solution, we have a string “456” that represents a numeric value.
  2.  Using  type casting we can  convert the string into an integer using the int() function and also, store the result in a variable called my_int.
  3. Input will be taken either string or a number using int() function it will be converted into an integer.
  4. The string “456” is converted to an integer with a value of 456, in this example.

Code:

string1 = "456"
my_int = int(string1)
print(my_int)

Output:

456

Conclusion

In this article, details of Python string and number values are given with explicit methods used to convert a string into numeric values. Sometimes there are many situations faced by the programmer, so it must be required to convert from one type to another data type.  With the help of an in-built function we can convert one data type to another data type.