Python Forum
How do I check if the first X characters of a string are numbers? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How do I check if the first X characters of a string are numbers? (/thread-39762.html)



How do I check if the first X characters of a string are numbers? - FirstBornAlbratross - Apr-11-2023

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?


RE: How do I check if the first X characters of a string are numbers? - menator01 - Apr-11-2023

You could use string splice and isdigit


RE: How do I check if the first X characters of a string are numbers? - deanhystad - Apr-11-2023

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



RE: How do I check if the first X characters of a string are numbers? - FirstBornAlbratross - Apr-11-2023

OK I figured it out.

String splice + check. (menator01's solution)

Simple.

Thanks for the replies.

All the best.


RE: How do I check if the first X characters of a string are numbers? - deanhystad - Apr-11-2023

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.


RE: How do I check if the first X characters of a string are numbers? - menator01 - Apr-12-2023

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



RE: How do I check if the first X characters of a string are numbers? - jefsummers - Apr-12-2023

Minor point that hopefully does not apply - neither solution works for negative numbers.