How to tell if string starts with a number with Python?
Solution 1:
Python's string
library has isdigit()
method:
string[0].isdigit()
Solution 2:
>>> string = '1abc'
>>> string[0].isdigit()
True
Solution 3:
Surprising that after such a long time there is still the best answer missing.
The downside of the other answers is using [0]
to select the first character, but as noted, this breaks on the empty string.
Using the following circumvents this problem, and, in my opinion, gives the prettiest and most readable syntax of the options we have. It also does not import/bother with regex either):
>>> string = '1abc'
>>> string[:1].isdigit()
True
>>> string = ''
>>> string[:1].isdigit()
False
Solution 4:
sometimes, you can use regex
>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>