0
0
PythonHow-ToBeginner · 3 min read

How to Check if String Starts with Number in Python

In Python, you can check if a string starts with a number by using str[0].isdigit() to test the first character or use the re.match() function with a pattern like r'^\d' to check if the string begins with a digit.
📐

Syntax

There are two common ways to check if a string starts with a number:

  • Using str[0].isdigit(): Checks if the first character of the string is a digit.
  • Using re.match() with pattern r'^\d': Uses regular expressions to check if the string starts with any digit.
python
string[0].isdigit()

import re
re.match(r'^\d', string) is not None
💻

Example

This example shows both methods to check if a string starts with a number and prints the result.

python
import re

def starts_with_number(s):
    # Method 1: Using str[0].isdigit()
    if s and s[0].isdigit():
        return True
    # Method 2: Using regex
    if re.match(r'^\d', s):
        return True
    return False

# Test strings
strings = ['123abc', 'abc123', '9lives', '', ' zero']

for text in strings:
    print(f"'{text}': {starts_with_number(text)}")
Output
'123abc': True 'abc123': False '9lives': True '': False ' zero': False
⚠️

Common Pitfalls

Common mistakes include:

  • Not checking if the string is empty before accessing str[0], which causes an error.
  • Using str.isdigit() on the whole string instead of just the first character.
  • Ignoring whitespace at the start, which may cause unexpected results.
python
s = ''
# Wrong: causes IndexError if string is empty
# if s[0].isdigit():
#     print('Starts with number')

# Right: check string is not empty first
if s and s[0].isdigit():
    print('Starts with number')
else:
    print('Does not start with number')
Output
Does not start with number
📊

Quick Reference

Summary tips to check if a string starts with a number:

  • Use str[0].isdigit() after confirming the string is not empty.
  • Use re.match(r'^\d', string) for pattern matching.
  • Trim whitespace if needed before checking.

Key Takeaways

Always check the string is not empty before accessing the first character.
Use str[0].isdigit() to quickly check if the first character is a digit.
Regular expressions with re.match(r'^\d', string) provide a flexible alternative.
Be mindful of leading whitespace which may affect the check.
Avoid using str.isdigit() on the whole string when only the start matters.