How to Check if a String Begins with a Number in Python?

In this tutorial, I will explain how to check if a string begins with a number in Python. As a Python developer working on an online registration system for a US-based website, I needed to validate usernames, the requirement is that usernames cannot begin with a number. After researching different methods, I discovered several ways to accomplish this task efficiently. In this article, I will share my findings with examples.

Methods to Check if a String Begins with a Number in Python

Let us see some important methods to check if a string begins with a number in Python.

Method 1. Use the startswith() Method

The startswith() method is a built-in Python function that checks if a string starts with a specified prefix. While it’s commonly used for checking if a string starts with another string, it can also be adapted to check for numeric prefixes.

Example

def starts_with_number(s):
    return s.startswith(tuple(str(i) for i in range(10)))

# Example usage
print(starts_with_number("123MainStreet"))   
print(starts_with_number("MainStreet123"))

Output:

True
False

I have executed the above example code and added the screenshot below.

Check if a String Begins with a Number in Python

In this example, we use a tuple of strings representing the digits 0-9 as the argument to startswith(). This way, the function checks if the string starts with any of these digits.

Read How to Create an Empty Tuple in Python?

Method 2. Use Regular Expressions

Regular expressions (regex) provide a powerful way to search for patterns in strings. The re module in Python allows us to use regex to check if a string begins with a number.

Example

import re

def starts_with_number(s):
    pattern = r'^\d'
    return bool(re.match(pattern, s))

# Example usage
print(starts_with_number("456ElmStreet"))  
print(starts_with_number("ElmStreet456"))  

Output:

True
False

I have executed the above example code and added the screenshot below.

How to Check if a String Begins with a Number in Python

In this example, r'^\d' is a regex pattern that matches any string starting with a digit. The re.match() function checks if the string matches this pattern from the beginning.

Check out How to Print a Tuple in Python?

Method 3. Use String Indexing and isdigit() Function

Another simple method involves checking the first character of the string using indexing and the isdigit() method.

Example

def starts_with_number(s):
    return s[0].isdigit() if s else False

# Example usage
print(starts_with_number("789PineStreet"))  
print(starts_with_number("PineStreet789")) 

Output:

True
False

I have executed the above example code and added the screenshot below.

Check if a String Begins with a Number in Python isdigit()

In this example, we check if the first character of the string is a digit using s[0].isdigit(). If the string is empty, we return False.

Check out How to Append Elements to a Tuple in Python?

Applications

Let us see some application that helps to understand better.

1. Validate User Input

Let’s say you have an application where users enter their addresses, and you want to ensure that the address starts with a house number.

def validate_address(address):
    if starts_with_number(address):
        print("Valid address")
    else:
        print("Invalid address")

# Example usage
validate_address("1234 Maple Avenue, New York, NY")  
validate_address("Maple Avenue, New York, NY")  
# Output: Valid address
# Output: Invalid address

Read How to Iterate Through Tuples in Python?

2. Filter Dataset Entries

Suppose you have a dataset of addresses and you want to filter out entries that start with a number.

addresses = [
    "1600 Pennsylvania Avenue, Washington, DC",
    "Broadway, New York, NY",
    "1 Infinite Loop, Cupertino, CA",
    "Wall Street, New York, NY"
]

filtered_addresses = [address for address in addresses if starts_with_number(address)]
print(filtered_addresses)  
# Output: ['1600 Pennsylvania Avenue, Washington, DC', '1 Infinite Loop, Cupertino, CA']

Check out How to Convert an Array to a Tuple in Python?

3. Handle File Names

If your application generates files that need to start with a number, you can use these methods to validate file names.

file_names = [
    "2024_report.pdf",
    "report_2024.pdf",
    "123_summary.docx",
    "summary_123.docx"
]

valid_files = [file for file in file_names if starts_with_number(file)]
print(valid_files)  
# Output: ['2024_report.pdf', '123_summary.docx']

Read Convert String to List in Python Without Using Split

Conclusion

In this tutorial, I have explained how to check if a string begins with a number in Python. Whether you choose to use the startswith() method, regular expressions , or string indexing with isdigit() , each approach has its advantages. We also discussed some useful applications.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.