Python Forum

Full Version: How do I check if the first X characters of a string are numbers?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How do I check if the first X characters of a string are numbers?

For example if someone inputs a combination of numbers and characters, how can I check to see if the first 3 characters are numbers?
You could use string splice and isdigit
Or a regular expression.

https://docs.python.org/3/library/re.html

import re

for string in ('123ab', '12.3ab', '12', '123', 'a123'):
    print(string, re.match(r'\d{3}.*', string))
Output:
123ab <re.Match object; span=(0, 5), match='123ab'> 12.3ab None 12 None 123 <re.Match object; span=(0, 3), match='123'> a123 None
OK I figured it out.

String splice + check. (menator01's solution)

Simple.

Thanks for the replies.

All the best.
menator's solution doesn't work if the string is shorter than 3 characters.
for string in ("123ab", "12.3ab", "12", "123", "a123"):
    print(string, string[:3].isdigit())
Output:
123ab True 12.3ab False 12 True 123 True a123 False
12 passes as a string that starts with 3 digits.
Could use an extra condition check

for string in ('123ab', '12.3ab', '12', '123', 'a123'):
    if string[:3].isdigit() and len(string[:3]) >= 3:
        print(string)
output:
Output:
123ab 123
Minor point that hopefully does not apply - neither solution works for negative numbers.