Convert Strings to Numbers in Python with Error Handling

1. Introduction

When programming in Python, data type conversion is a crucial technique. In particular, the ability to convert between strings and numbers is essential for data input/output and calculations. For example, you often need to convert a string entered by a user in a form into a number for computation, or format a numeric result as a string for display. However, mixing data of different types can cause errors, so beginners need to be careful. This article introduces how to convert “strings to numbers” and “numbers to strings” in Python, providing practical examples and detailed coverage of error handling and special cases. We hope it helps you develop skills ranging from basic to advanced Python programming. The next section will explain Python’s basic type conversion methods in detail.

2. Basic Type Conversion in Python

In Python, when data types differ, direct operations are often limited, and it is necessary to convert data between different types. Understanding how to convert strings to numbers, or the reverse, enables you to write more flexible and error‑free code. This section explains basic type conversion in Python using the “int()” and “float()” functions.

Conversion to Integer

When a number is entered as a string, you need to convert that string to an integer or a floating‑point number before performing numeric calculations in Python. For example, to convert the string “42” to an integer 42, you use the int() function as follows.
str_number = "42"
int_number = int(str_number)
print(int_number)  # Output: 42
Thus, using the int() function makes it possible to convert a string to an integer. When the conversion succeeds, the value can be used as a number. Note that attempting to convert a string containing a decimal point, such as "42.0", to an integer type will raise an error. Only whole numbers are valid for integer conversion; if the string includes a decimal point, you need to use float().

Conversion to Floating‑Point Number

A floating‑point number is a type that can retain the fractional part of a value. In Python, you can convert a string to a floating‑point number using the float() function. For example, to convert the string “3.14” to a floating‑point number, use the following code.
str_float = "3.14"
float_number = float(str_float)
print(float_number)  # Output: 3.14
Thus, using the float() function allows conversion from a string to a floating‑point number. Additionally, strings in scientific notation can be converted with float(), and notations such as "1.23e-4" are also supported.
str_exp = "1.23e-4"
float_exp = float(str_exp)
print(float_exp)  # Output: 0.000123

Conversion from Number to String

Conversely, there are many situations where you need to convert a number to a string. For example, when you want to concatenate a number with other strings for display. In such cases, you use the str() function.
num = 42
str_num = str(num)
print("Result of converting a number to a string: " + str_num)  # Output: Result of converting a number to a string: 42
Thus, the str() function performs conversion from a number to a string, enabling manipulation of strings that contain numbers. Once you understand basic type conversion, you can move on to advanced topics such as converting between other numeral systems and handling full‑width strings.
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

3. Application Example: Conversion of Multiple Bases and Full-Width Numbers

Now that you understand Python’s basic type conversions, we’ll discuss more advanced cases. This section explains how to convert to various bases such as binary and hexadecimal, and how to handle numbers that include full-width characters.

Conversion of Binary, Octal, and Hexadecimal

Python’s int() function can convert not only decimal but also binary, octal, and hexadecimal strings. In this case, you specify the base (radix) as the second argument to the int() function. For example, to convert binary or hexadecimal strings to integers, you would write as follows.
binary_str = "1010"  # binary string
octal_str = "12"  # octal string
hex_str = "a"  # hexadecimal string

int_binary = int(binary_str, 2)
int_octal = int(octal_str, 8)
int_hex = int(hex_str, 16)

print(int_binary)  # Output: 10
print(int_octal)  # Output: 10
print(int_hex)  # Output: 10
Thus, binary, octal, and hexadecimal strings can also be converted to integers by using int() with the appropriate base. This feature is especially useful when working with data that involves multiple numeral systems.

Handling Full-Width Numbers and Special Characters

If a string from user input contains full-width numbers or special characters, attempting to convert it directly in Python can raise errors. Especially when Japanese numeric input includes full-width characters, Python often cannot handle them properly, so it is recommended to use the replace() method to convert full-width characters to half-width. Below is an example that converts a full-width string to half-width before converting it to a number.
str_num_fullwidth = "12345"
str_num_halfwidth = str_num_fullwidth.translate(str.maketrans('0123456789', '0123456789'))

print(int(str_num_halfwidth))  # Output: 12345
Using this approach allows full-width numeric strings to be converted to numbers. If the full-width decimal point also needs conversion, you can perform an additional conversion as follows.
str_float_fullwidth = "123.456"
str_float_halfwidth = str_float_fullwidth.translate(str.maketrans('0123456789.', '0123456789.'))

print(float(str_float_halfwidth))  # Output: 123.456

Conversion of Kanji Numerals

In Python, you can use the Unicode module to convert some kanji numerals to numbers. By using unicodedata.numeric(), strings such as “一” or “百” can be converted to floating-point numbers.
import unicodedata

kanji_num = '五'
converted_num = unicodedata.numeric(kanji_num)
print(converted_num)  # Output: 5.0
However, it does not support kanji numerals that consist of multiple characters (e.g., “十五”), so for more complex processing you should consider additional libraries or custom regular‑expression handling. Thus, Python offers a variety of conversion methods even for numeric strings. The next section will detail how to determine whether an input value can be converted and how to handle errors.

4. Error Handling and Input Validation

In data processing, there are cases where user input data or data received from external sources cannot be properly converted to numbers. Therefore, it is important to determine in advance whether the data can be converted to a numeric type, and to handle errors appropriately when conversion fails. This section explains methods for input validation and error handling.

Number Detection Using isdigit() and Regular Expressions

One way to pre‑determine whether a string can be converted to a number is to use Python’s isdigit() method or regular expressions. isdigit() returns True when the string consists entirely of digits, but returns False if it contains a decimal point or a minus sign. Therefore, it is useful when you want to check for integers only.
def is_integer(input_str):
    return input_str.isdigit()

# Example usage
print(is_integer("123"))  # Output: True
print(is_integer("3.14"))  # Output: False
print(is_integer("-123"))  # Output: False
On the other hand, for number detection that includes floating‑point numbers and negative values, regular expressions are convenient. In the example below, numbers prefixed with “+” or “-” and values containing a decimal point are set to return True.
import re

def is_numeric(input_str):
    return bool(re.match(r'^[+-]?d+(.d+)?$', input_str))

# Example usage
print(is_numeric("123"))       # Output: True
print(is_numeric("-123.45"))   # Output: True
print(is_numeric("3.14.15"))   # Output: False
print(is_numeric("abc"))       # Output: False
By using regular expressions in this way, you can more flexibly determine whether a value is numeric, which is helpful when processing complex input data.

Error Handling: Using Exception Handling

In Python, converting a string to a number with inappropriate data raises an error (ValueError). To catch this error and continue processing, it is common to use a try-except block for exception handling. In the example below, if an error occurs while attempting to convert a string to an integer, an appropriate error message is displayed.
def convert_to_int(input_str):
    try:
        return int(input_str)
    except ValueError:
        print(f"Error: '{input_str}' cannot be converted to an integer.")
        return None

# Example usage
print(convert_to_int("123"))  # Output: 123
print(convert_to_int("abc"))  # Output: Error: 'abc' cannot be converted to an integer.
By adding exception handling, the program can continue running smoothly even when errors occur, without stopping. It also provides clear feedback to the user, making it easier to address input mistakes. When input data validation and error handling are performed properly, the reliability of the code improves. In the next section, we will look at how to convert list elements in bulk.

5. How to Convert List Elements in Bulk

When processing data, you may need to convert list elements that are in string format to numbers in bulk. For example, CSV files and data retrieved from external sources are often stored as strings. This section introduces a method for bulk conversion using Python list comprehensions.

Bulk Conversion Using List Comprehensions

In Python, in addition to processing each list element with a loop, you can use list comprehensions to perform data conversion concisely and efficiently. A list comprehension applies a specific operation to each element of a list and generates a new list. For example, to convert a list containing numeric strings to a list of integers, use the following code.
str_list = ["10", "20", "30", "40", "50"]
int_list = [int(i) for i in str_list]

print(int_list)  # Output: [10, 20, 30, 40, 50]
In this example, the [int(i) for i in str_list] of the list comprehension causes each element in str_list to be converted to an integer using the int() function, creating a new list int_list. This approach allows large‑scale data processing with concise code, improving code readability and performance.

Bulk List Conversion with Error Handling

If the list contains data that cannot be converted (e.g., strings or special characters), an error occurs. In this case, you can incorporate conditions or exception handling into the list comprehension to avoid conversion errors. Below is an example that converts only the elements that can be converted to integers.
str_list = ["10", "20", "abc", "30", "40"]

int_list = []
for i in str_list:
    try:
        int_list.append(int(i))
    except ValueError:
        print(f"Warning: '{i}' could not be converted to an integer.")

print(int_list)  # Output: [10, 20, 30, 40]
In this code, the try-except block is used to convert strings to integers, and if conversion fails, an error message is displayed. By adding only the convertible elements to int_list using the append() method, processing continues even if errors occur, and you obtain the conversion results. Bulk list conversion is a very useful technique for processing large amounts of data. In the next section, we will summarize the entire article and organize what we have learned.

6. Summary

In this article, we explained how to convert between strings and numbers in Python, covering basics to advanced topics. Understanding the importance of type conversion in data processing and how to do it efficiently expands the range of operations you can perform in Python programming. Below is a brief summary of each section.

Article recap

  1. Introduction
  • We explained situations where converting between strings and numbers is necessary, and showed why type conversion is important for numerical calculations and data display.
  1. Basic type conversion in Python
  • We learned the basic conversion methods, using int(), float(), and the str() function to change data types between strings and numbers.
  1. Advanced examples: conversion of various bases and full-width numbers
  • We introduced how to convert binary, octal, and hexadecimal numbers to integers, and how to convert full-width characters to half-width for numeric handling. We also explained how to convert kanji numerals to numbers using unicodedata.numeric().
  1. Error handling and input validation
  • Considering that errors can occur during numeric conversion, we showed how to pre‑validate whether a value is numeric using isdigit() and regular expressions, and how to handle errors with exception handling using try-except.
  1. How to convert list elements in bulk
  • We learned how to perform bulk conversion using list comprehensions, how to handle errors that may arise, and gained skills to process large amounts of data efficiently.

Future applications

Type conversion in Python is involved in virtually every data processing and basic programming operation. By consistently applying proper type conversion and error handling in real‑world development, you can reduce bugs and write higher‑quality code. Moreover, building on the basic conversion methods learned here and mastering more advanced data‑conversion techniques will enable you to handle complex data processing efficiently. We hope this article has given you a comprehensive understanding of the knowledge and techniques needed for type conversion in Python. Apply what you’ve learned to your future programming projects.