How to Check If a String Is a Number in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you'll learn how to determine if a string in Python represents a number. We'll start by defining various strings, some of which resemble numbers, in a Python script named numeric_strings.py. This script will print these strings to the console, setting the stage for subsequent analysis.

Next, we'll explore the isdigit() method to identify strings containing only digits, indicating non-negative integers. This method is crucial for validating data and ensuring safe conversions to numeric types.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python/BasicConceptsGroup -.-> python/strings("Strings") python/BasicConceptsGroup -.-> python/type_conversion("Type Conversion") python/FunctionsGroup -.-> python/build_in_functions("Build-in Functions") python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") subgraph Lab Skills python/strings -.-> lab-559573{{"How to Check If a String Is a Number in Python"}} python/type_conversion -.-> lab-559573{{"How to Check If a String Is a Number in Python"}} python/build_in_functions -.-> lab-559573{{"How to Check If a String Is a Number in Python"}} python/catching_exceptions -.-> lab-559573{{"How to Check If a String Is a Number in Python"}} end

Define Numeric Strings

In this step, we'll explore how Python handles strings that represent numbers. These are called "numeric strings." Understanding how to identify and work with them is crucial for data validation and manipulation.

A numeric string is simply a string that contains only characters that can be interpreted as a number. This could be an integer, a floating-point number, or even a number in scientific notation.

Let's start by creating a Python script to examine some examples.

  1. In the VS Code editor, create a new file named numeric_strings.py in your ~/project directory.

  2. Add the following code to the numeric_strings.py file:

## Define some strings
string1 = "123"
string2 = "3.14"
string3 = "-42"
string4 = "0"
string5 = "  56  "
string6 = "abc"
string7 = "123.45.67"
string8 = "1e10"

## Print the strings
print(f"String 1: {string1}")
print(f"String 2: {string2}")
print(f"String 3: {string3}")
print(f"String 4: {string4}")
print(f"String 5: {string5}")
print(f"String 6: {string6}")
print(f"String 7: {string7}")
print(f"String 8: {string8}")
  1. Save the numeric_strings.py file.

  2. Now, run the script from the terminal:

python numeric_strings.py

You should see the following output:

String 1: 123
String 2: 3.14
String 3: -42
String 4: 0
String 5:   56
String 6: abc
String 7: 123.45.67
String 8: 1e10

As you can see, we've defined several strings, some of which look like numbers. In the following steps, we'll learn how to determine which of these strings can be safely converted to numeric types.

Use isdigit() for Integers

In this step, we'll learn how to use the isdigit() method to check if a string contains only digits and represents a non-negative integer. This method is particularly useful for validating user input or data read from files.

The isdigit() method is a built-in string method in Python. It returns True if all characters in the string are digits and there is at least one character, and False otherwise.

Let's modify our previous script to use isdigit():

  1. Open the numeric_strings.py file in the VS Code editor.

  2. Modify the code to include the isdigit() method as follows:

## Define some strings
string1 = "123"
string2 = "3.14"
string3 = "-42"
string4 = "0"
string5 = "  56  "
string6 = "abc"
string7 = "123.45.67"
string8 = "1e10"

## Check if the strings are digits
print(f"String 1 '{string1}' isdigit(): {string1.isdigit()}")
print(f"String 2 '{string2}' isdigit(): {string2.isdigit()}")
print(f"String 3 '{string3}' isdigit(): {string3.isdigit()}")
print(f"String 4 '{string4}' isdigit(): {string4.isdigit()}")
print(f"String 5 '{string5}' isdigit(): {string5.isdigit()}")
print(f"String 6 '{string6}' isdigit(): {string6.isdigit()}")
print(f"String 7 '{string7}' isdigit(): {string7.isdigit()}")
print(f"String 8 '{string8}' isdigit(): {string8.isdigit()}")
  1. Save the numeric_strings.py file.

  2. Run the script from the terminal:

python numeric_strings.py

You should see the following output:

String 1 '123' isdigit(): True
String 2 '3.14' isdigit(): False
String 3 '-42' isdigit(): False
String 4 '0' isdigit(): True
String 5 '  56  ' isdigit(): False
String 6 'abc' isdigit(): False
String 7 '123.45.67' isdigit(): False
String 8 '1e10' isdigit(): False

As you can see, isdigit() only returns True for strings that contain only digits. It returns False for strings containing decimal points, negative signs, spaces, or any non-digit characters.

This method is useful for verifying if a string can be safely converted to an integer without raising an error. However, it's important to remember that isdigit() only works for non-negative integers. For other numeric types, we'll need to use different approaches, as we'll see in the next step.

Try float() Conversion

In this step, we'll explore how to use the float() function to convert strings to floating-point numbers. This is useful when you need to work with numbers that have decimal points or are represented in scientific notation.

The float() function is a built-in function in Python that attempts to convert its argument to a floating-point number. If the argument is a string, it must be a valid representation of a floating-point number.

Let's modify our script again to use float() and see how it handles different strings:

  1. Open the numeric_strings.py file in the VS Code editor.

  2. Modify the code to include the float() function and handle potential errors:

## Define some strings
string1 = "123"
string2 = "3.14"
string3 = "-42"
string4 = "0"
string5 = "  56  "
string6 = "abc"
string7 = "123.45.67"
string8 = "1e10"

## Try converting the strings to floats
strings = [string1, string2, string3, string4, string5, string6, string7, string8]

for s in strings:
    try:
        float_value = float(s)
        print(f"String '{s}' can be converted to float: {float_value}")
    except ValueError:
        print(f"String '{s}' cannot be converted to float")
  1. Save the numeric_strings.py file.

  2. Run the script from the terminal:

python numeric_strings.py

You should see the following output:

String '123' can be converted to float: 123.0
String '3.14' can be converted to float: 3.14
String '-42' can be converted to float: -42.0
String '0' can be converted to float: 0.0
String '  56  ' can be converted to float: 56.0
String 'abc' cannot be converted to float
String '123.45.67' cannot be converted to float
String '1e10' can be converted to float: 10000000000.0

As you can see, float() can successfully convert strings that represent integers, decimal numbers, and numbers in scientific notation. It also automatically removes leading and trailing whitespace (as demonstrated by string5). However, it raises a ValueError if the string cannot be interpreted as a valid floating-point number (as demonstrated by string6 and string7).

Using try-except blocks allows us to handle these potential errors gracefully and prevent our program from crashing. This is a common and important practice when working with user input or data from external sources.

Summary

In this lab, we began by defining numeric strings in Python, which are strings containing characters that can be interpreted as numbers (integers, floats, etc.). We created a numeric_strings.py script to define and print various strings, including integers, decimals, and strings with non-numeric characters, to illustrate different string formats.

Next, we started exploring the isdigit() method to check if a string contains only digits, indicating a non-negative integer. The lab is set to continue demonstrating how to use this method for validating strings.