- Extract decimal numbers from a string in Python
- Using findall() function
- Example
- Output
- Convert a String to Decimal in Python
- Syntax:
- Method 1: Convert a String to Decimal using float()
- Syntax:
- Parameter:
- Example:
- Output:
- Method 2: Convert a String to Decimal using numpy.float_()
- Syntax:
- Parameter:
- Example 1:
- Output:
- Example 2:
- Output:
- Method 3: Convert a String to Decimal using Decimal()
- Syntax:
- Parameter:
- Example:
- Output:
- Summary
- Related Post
- Convert String to Decimal in Python
- Use the float() Function to Convert a String to Decimal in Python
- Use Exception Handling Convert a String Containing a Comma to a String in Python
- Use String Formatting Along With the float() Function to Convert a String to Decimal in Python
- Use List Comprehension to Convert a List of Strings to Float in Python
- Use numpy.float() Function to Convert a String to Decimal in Python
- Use the astype() Method From the NumPy Library to Convert a String to Decimal in Python
- Use the decimal Module to Convert a String to Decimal in Python
- Related Article — Python String
- Related Article — Python Float
Extract decimal numbers from a string in Python
To extract decimal numbers from a string in python, regular expressions are used.
A regular expression is a group of characters that allows you to use a search pattern to find a string or a set of strings. RegEx is another name for regular expressions.
The re module in Python is used to work with regular expressions.
In this article, we will get to know how to extract decimal numbers from a string in python using regular expressions.
We use \d+\.\d+ regular expression in python to get non digit characters from a string.
- \d returns a match where the string contains digits (numbers from 0 9)
- + implies zero or more occurrences of characters.
- \ signals a special sequence (can also be used to escape special characters).
- . is any character (except newline character).
Using findall() function
In the following example, let us assume ‘Today’s temperature is 40.5 degrees.’ as a string. Here, we need to extract decimal number 40.5 from the string.
Example
The following is an example code through which the decimals are extracted from a string in python. We begin by importing regular expression module.
Then, we have used findall() function which is imported from the re module.
import re string = "Today's temperature is 40.5 degrees." x=re.findall("\d+\.\d+",string) print(x)
The re.findall() function returns a list containing all matches, that is list of strings with non-digits.
Output
On executing the above code snippet, the below output is obtained.
Convert a String to Decimal in Python
In this blog, we will see how to convert the given string into Decimal in Python. There are several ways to convert the given input string into decimal.
In this blog, we will see how to convert the given string into Decimal in Python. There are several ways to convert the given input string into decimal. Let’s see them one by one.
Before going to discuss, If we want to return the type of the variable in python, then we can use the type() method.
Syntax:
Where the variable holds the value.
We can use the below methods to convert a String to Decimal,
- Convert a String to Decimal using float()
- Convert a String to Decimal using numpy.float_()
- Convert a String to Decimal using decimal.Decimal()
Method 1: Convert a String to Decimal using float()
float() in Python converts the string with numeric data into decimals. If we display the type of the converted string, then class-float is returned.
No built-in module is required to use this method.
Syntax:
Parameter:
It takes only one parameter. IE string.
Example:
Convert the string — ‘58.99’ into decimal using the float() method.
# Input string string_1='58.99' print("Actual string: ", string_1) print("Actual string type: ", type(string_1)) # Convert into float print("Final value: ", float(string_1)) print("Final string type: ", type(float(string_1)))
Output:
Actual string: 58.99 Final value: 58.99 Actual string type: Final string type:
We can see that before the variable type is str (string) , it is float.
Method 2: Convert a String to Decimal using numpy.float_()
float_() in Python is available in the numpy module that converts the string that has numeric data into decimal. It is similar to the first method.
This method is useful if we store the string values in numpy arrays.
Syntax:
numpy.float_(string/numpy_array)
Parameter:
It takes only one parameter. IE string or numpy_array that have strings.
Example 1:
Convert the string — ‘58.99’ into decimal using numpy.float_() method.
# Import the numpy module import numpy # Input string string_1='58.99' print("Actual string: ", string_1) print("Final value: ", numpy.float_(string_1)) print("Final string type: ", type(numpy.float_(string_1)))
Output:
Actual string: 58.99 Final value: 58.99 Final string type:
We can see that before the type of variable type is str (string) , float.
Example 2:
Now convert the strings present in the numpy array into decimal using numpy.float_() method.
# Import the numpy module import numpy # Input strings array=numpy.array(['58.99','45.67','78.89']) print("Actual strings: ", array) # Convert into float print("Final value: ", numpy.float_(array))
Output:
Actual strings: ['58.99' '45.67' '78.89'] Final value: [58.99 45.67 78.89]
Method 3: Convert a String to Decimal using Decimal()
Decimal() in Python is available in the decimal module that converts the string or float value into decimal and returns the type as a decimal.Decimal() .
It is important to import this module, Otherwise, you will get a module not found error.
Syntax:
Parameter:
It takes only one parameter. IE string.
Example:
Convert the string — ‘58.99’ into decimal using decimal.Decimal() method.
# Import the Decimal method from decimal module from decimal import Decimal # Input string string_1='58.99' print("Actual string: ",string_1) print("Actual string type: ",type(string_1)) print("Final value: ",Decimal(string_1)) print("Final string type: ",type(Decimal(string_1)))
Output:
Actual string: 58.99 Actual string type: Final value: 58.99 Final string type:
We can see that before the type of the variable is str (string), and After that it is decimal.
Summary
So by the end of this blog, we have seen how to convert the string into decimal using three methods.
Related Post
Convert String to Decimal in Python
- Use the float() Function to Convert a String to Decimal in Python
- Use Exception Handling Convert a String Containing a Comma to a String in Python
- Use String Formatting Along With the float() Function to Convert a String to Decimal in Python
- Use List Comprehension to Convert a List of Strings to Float in Python
- Use numpy.float() Function to Convert a String to Decimal in Python
- Use the astype() Method From the NumPy Library to Convert a String to Decimal in Python
- Use the decimal Module to Convert a String to Decimal in Python
Strings in Python can take numeric values. Similar to other popular programming languages, Python supports Integer and Floating-point (or decimal) numbers and has separate data types assigned for them. Sometimes, there is a need for converting the numeric values taken in a string to an integer or a floating-point number.
This tutorial will introduce how to convert a string to a decimal in Python.
Use the float() Function to Convert a String to Decimal in Python
Python provides an in-built function called float() that is utilized to transform a string or an integer to a floating-point value.
Here, we will enter a string and perform the float() function on the given string.
The following code uses the float() function to convert a string to decimal in Python.
The above code provides the following output:
Use Exception Handling Convert a String Containing a Comma to a String in Python
When a comma separates the numbers in the string and the float() function is directly called on the string, then it gives a ValueError .
The following example code will help you understand it better.
The above code provides the following output:
Traceback (most recent call last): File "", line 2, in ValueError: could not convert string to float: '1,5.54'
We can take a quick detour from the original code and use exception handling in this code to avoid this.
- The try block contains the cluster of code to be tested for any errors.
- The except block is used to add exceptions and handle the errors of the code.
- The finally block contains the statements that need to be executed and is ignored by the try and except blocks.
The following code utilizes exception handling on the original code given above to convert a string to decimal in Python.
a = "1,5.54" try: x = float(a) except ValueError: print("Invalid Float number to be converted. ")
The above code provides the following output:
Invalid Float number to be converted.
Use String Formatting Along With the float() Function to Convert a String to Decimal in Python
In a given string, if we want to specify the number of decimal points that we want to have in the floating-point variable, then we can use string formatting along with the in-built float() function.
The following code uses string formatting to convert a string to decimal in Python.
a = "5.54231" x = float(a) x = " ".format(x) print(x)
The above code provides the following output:
Use List Comprehension to Convert a List of Strings to Float in Python
List comprehension is a relatively shorter and very graceful way to create lists that are to be formed based on given values of an already existing list.
We can use list comprehension and convert all the values within the list to floating-point values using the float() method in the list comprehension.
The following code uses list comprehension to convert a list of strings to float in Python.
lst= [ '1.22', '5.54', '6.858'] x = [float(i) for i in lst] print(x)
The above code provides the following output.
Use numpy.float() Function to Convert a String to Decimal in Python
The term NumPy is an acronym for Numerical Python. This library makes the use of arrays possible in Python. It also provides functions that help in manipulating these arrays.
The numpy.float() function works similarly to the in-built float() function in Python, with the only difference being that the numpy.float() function is made to work with arrays. It always generates an array of floating-point values.
The following code uses the numpy.float() function to convert a string to decimal in Python.
import numpy as np lst= [ '1.22', '5.54', '6.858'] print(list(np.float_(lst)))
The above code provides the following output:
Use the astype() Method From the NumPy Library to Convert a String to Decimal in Python
The NumPy library contains an in-built astype() method that assists in converting the data type of the given NumPy array.
The following code uses the astype() method from the NumPy library to convert a string to decimal in Python.
import numpy as np a = np.array(["1.22", "5.54", "6.858"]) x = a.astype(float) print(x)
The above code provides the following output:
Use the decimal Module to Convert a String to Decimal in Python
The decimal module supplies functions that perform faster operations than the stock floating-point functions.
The decimal.Decimal() function, which is a constructor, takes input as a numeric value and carries out the process to convert it to a decimal type, which is ideal for storing and representing the numeric values meanwhile strictly preserving the precision of the number.
The following code uses the decimal module to convert a string to decimal in Python.
from decimal import Decimal a = '5.54262' x = Decimal(a) print(x)
The above code provides the following output:
Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.
Related Article — Python String
Related Article — Python Float
Copyright © 2023. All right reserved