How to determine if a string starts with a number?

I have a line that starts with a number (from 0 to 9) I know I can "or" 10 test cases using startswith (), but maybe there is a tidier 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 smarter / more efficient way?

+48
python
Apr 7 2018-11-11T00:
source share
10 answers

The Python string library has an isdigit() method:

 string[0].isdigit() 
+93
Apr 7 2018-11-11T00:
source share
 >>> string = '1abc' >>> string[0].isdigit() True 
+22
Apr 07 2018-11-11T00:
source share

sometimes you can use regex

 >>> import re >>> re.search('^\s*[0-9]',"0abc") <_sre.SRE_Match object at 0xb7722fa8> 
+5
Apr 7 2018-11-11T00:
source share

Your code will not 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')) 
+5
Apr 7 2018-11-11T00:
source share
 for s in ("fukushima", "123 is a number", ""): print s.ljust(20), s[0].isdigit() if s else False 

result

 fukushima False 123 is a number True False 
+3
May 6 '11 at 19:07
source share

You can also use try...except :

 try: int(string[0]) # do your stuff except: pass # or do your stuff 
+2
Jul 26 '17 at 16:42 on
source share

Here are my β€œanswers” ​​(trying to be unique here, I really don't recommend for this particular case :-)

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

 //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 pretty neat: compare 1 < 2 < 3 (true) and 1 < 3 < 2 (false) and (1 < 3) < 2 (true). This isn 'how it works in most other languages.)

Using regex :

 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 
+1
Apr 7 2018-11-11T00:
source share

Use Regular Expressions if you are going to somehow extend the functionality of the method.

0
Apr 07 2018-11-11T00:
source share

You can use regular expressions .

You can detect numbers using:

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

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

0
Apr 07 2018-11-11T00:
source share

Try the following:

 if string[0] in range(10): 
-5
Apr 07 2018-11-11T00:
source share



All Articles