How to tell if string starts with a number with Python? How to tell if string starts with a number with Python? python python

How to tell if string starts with a number with Python?


Python's string library has isdigit() method:

string[0].isdigit()


>>> string = '1abc'>>> string[0].isdigit()True


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