Converting Strings to Numbers in Python: Using int/float and Validation Logic

Data obtained from file imports or user inputs is initially treated as “strings (str)”. To use this data for calculations, it must be converted to the appropriate numeric type (int or float).

In this article, I will explain the basic conversion methods and how to implement check functions to prevent conversion errors.

目次

Table of Contents

  1. Converting strings to integers: int()
  2. Converting strings to floating-point numbers: float()
  3. Checking if conversion is possible (Safe Conversion)
  4. Summary

1. Converting strings to integers: int()

To convert a string to an integer, use the built-in function int().

Syntax:

number_variable = int(string_variable)

Basic Usage Example

text = "1222"

# Convert string to integer
num = int(text)

print(f"Value: {num}")
print(f"Type : {type(num)}")

Execution Result:

Value: 1222
Type : <class 'int'>

Note: Decimal strings cannot be converted directly

Passing a string containing a decimal point (e.g., "1.2") to the int() function will cause a ValueError.

# This will cause an error
# int("1.2") 
# -> ValueError: invalid literal for int() with base 10: '1.2'

If the string is in a decimal format, you must either convert it using float() first and then cast to int, or handle it as a float from the beginning.


2. Converting strings to floating-point numbers: float()

To convert a string to a floating-point number (decimal), use the built-in function float().

Syntax:

number_variable = float(string_variable)

Basic Usage Example

text = "3.14159"

# Convert string to float
num = float(text)

print(f"Value: {num}")
print(f"Type : {type(num)}")

Execution Result:

Value: 3.14159
Type : <class 'float'>

3. Checking if conversion is possible (Safe Conversion)

If you try to convert a non-numeric string (e.g., "abc"), the program will stop with an error. To prevent this, it is common to create a function that “attempts conversion and returns False if it fails.”

Although Python has methods like isdigit(), they may not support “negative signs” or “decimal points.” Therefore, using a try-except block is the most reliable method.

Implementation Example of Validation Functions

def is_int(val):
    """
    Function to check if convertible to integer
    """
    try:
        # Try actual conversion
        int(val)
        return True
    except ValueError:
        # Return False if conversion fails
        return False

def is_float(val):
    """
    Function to check if convertible to float
    """
    try:
        float(val)
        return True
    except ValueError:
        return False

# --- Verification ---

# Integer check
print(f"Is '3' an integer?   : {is_int('3')}")         # True
print(f"Is '3.5' an integer? : {is_int('3.5')}")     # False (int("3.5") causes error)
print(f"Is 'abc' an integer? : {is_int('abc')}")     # False

# Float check
print(f"Is '23.2' a float?   : {is_float('23.2')}")  # True
print(f"Is 'abc' a float?    : {is_float('abc')}")   # False

Execution Result:

Is '3' an integer?   : True
Is '3.5' an integer? : False
Is 'abc' an integer? : False
Is '23.2' a float?   : True
Is 'abc' a float?    : False

Summary

  • int(str): Converts integer-formatted strings. Passing a decimal format (e.g., "1.2") causes an error.
  • float(str): Converts decimal-formatted strings.
  • Conversion Check: Using try-except ValueError to test if the conversion is actually possible is the safest and most versatile approach.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次