
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Parse String to Float or Int in Python
Python provides built-in functions to convert strings into numerical data types like integers and floats. However, it's crucial to handle errors that may arise when a string cannot be properly converted (eg, trying to convert "abc" to an integer). Following are several methods to parse a string to float or int.
Using int() and float() with Error Handling
The most straightforward approach is using the int() and float() functions directly within a try-except block to catch ValueError exceptions.
Example
In the following example, the try block attempts to convert the string. If the conversion fails, a ValueError is raised. The except block catches the ValueError and executes the error-handling code.
try: integer_value = int("123") print("Integer value:", integer_value) except ValueError: print("Error: Could not convert string to integer.") # Parsing to Float try: float_value = float("3.14") print("Float value:", float_value) except ValueError: print("Error: Could not convert string to float.") try: integer_value = int("abc") except ValueError: print("Error: Could not convert 'abc' to integer.")
Following is the output for the above code-
Integer value: 123 Float value: 3.14 Error: Could not convert 'abc' to integer.
Using isdigit() for Integers (with validation)
Before attempting to convert to an integer, you can use the isdigit() method to check if the string contains only digits. This can prevent ValueError exceptions.
Example
In the following example, the isdigit() function returns True if all characters in the string are digits; otherwise, it returns False.
string_value = "456" if string_value.isdigit(): integer_value = int(string_value) print("Integer value:", integer_value) else: print("Error: String contains non-digit characters.") string_value = "78.9" # Contains a decimal point if string_value.isdigit(): integer_value = int(string_value) print("Integer value:", integer_value) else: print("Error: String contains non-digit characters.")
Following is the output for the above code-
Integer value: 456 Error: String contains non-digit characters.
Using Regular Expressions
Python Regular expressions provide a powerful way to validate the format of the string before conversion, allowing for more complex patterns like negative numbers, decimals, or specific formatting.
Example
In the following example, the re.match(pattern, string) attempts to match the pattern at the beginning of the string.
import re # For integers (allowing optional leading minus sign) string_value = "-123" if re.match(r"^-?\d+$", string_value): integer_value = int(string_value) print("Integer value:", integer_value) else: print("Error: Invalid integer format.") # For floats (allowing optional leading minus sign and decimal point) string_value = "-3.14" if re.match(r"^-?\d*\.?\d+$", string_value): float_value = float(string_value) print("Float value:", float_value) else: print("Error: Invalid float format.") string_value = "123a" if re.match(r"^-?\d*\.?\d+$", string_value): float_value = float(string_value) print("Float value:", float_value) else: print("Error: Invalid float format.")
Following is the output for the above code-
Integer value: -123 Float value: -3.14 Error: Invalid float format.