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

I have a string that starts with a number (from 0-9) I know I can "or" 10 test cases using startswith() but there is probably a neater solution

so instead of writing

if (string.startswith('0') || string.startswith('2') ||
    string.startswith('3') || string.startswith('4') ||
    string.startswith('5') || string.startswith('6') ||
    string.startswith('7') || string.startswith('8') ||
    string.startswith('9')):
    #do something

Is there a cleverer/more efficient way?

This question is related to python string digits

The answer is


You could use regular expressions.

You can detect digits using:

if(re.search([0-9], yourstring[:1])):
#do something

The [0-9] par matches any digit, and yourstring[:1] matches the first character of your string


Try this:

if string[0] in range(10):

You can also use try...except:

try:
    int(string[0])
    # do your stuff
except:
    pass # or do your stuff

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

sometimes, you can use regex

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>

This piece of code:

for s in ("fukushima", "123 is a number", ""):
    print s.ljust(20),  s[0].isdigit() if s else False

prints out the following:

fukushima            False
123 is a number      True
                     False

Here are my "answers" (trying to be unique here, I don't actually recommend either for this particular case :-)

Using ord() and the special a <= b <= c form:

//starts_with_digit = ord('0') <= ord(mystring[0]) <= ord('9')
//I was thinking too much in C. Strings are perfectly comparable.
starts_with_digit = '0' <= mystring[0] <= '9'

(This a <= b <= c, like a < b < c, is a special Python construct and it's kind of neat: compare 1 < 2 < 3 (true) and 1 < 3 < 2 (false) and (1 < 3) < 2 (true). This isn't how it works in most other languages.)

Using a regular expression:

import re
//starts_with_digit = re.match(r"^\d", mystring) is not None
//re.match is already anchored
starts_with_digit = re.match(r"\d", mystring) is not None

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

Your code won't work; you need or instead of ||.

Try

'0' <= strg[:1] <= '9'

or

strg[:1] in '0123456789'

or, if you are really crazy about startswith,

strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))

Use Regular Expressions, if you are going to somehow extend method's functionality.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to digits

C++ - how to find the length of an integer Gets last digit of a number Sum the digits of a number Get number of digits with JavaScript How do I separate an integer into separate digits in an array in JavaScript? C: how to break apart a multi digit number into separate variables? Show a leading zero if a number is less than 10 How to tell if string starts with a number with Python? in python how do I convert a single digit number into a double digits string? Controlling number of decimal digits in print output in R