117

我有一个以数字开头的字符串(0-9)

所以而不是写

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

有没有更聪明/更有效的方法?

4

12 回答 12

211

Python的string库有isdigit()方法:

string[0].isdigit()
于 2011-04-07T07:37:03.563 回答
30
>>> string = '1abc'
>>> string[0].isdigit()
True
于 2011-04-07T07:37:03.597 回答
14

令人惊讶的是,经过这么长时间,仍然缺少最佳答案。

其他答案的缺点是[0]用于选择第一个字符,但如前所述,这会在空字符串上中断。

使用以下内容可以绕过这个问题,并且在我看来,它给出了我们拥有的选项的最漂亮和最易读的语法。它也不会导入/使用正则表达式):

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

>>> string = ''
>>> string[:1].isdigit()
False
于 2019-08-09T14:11:10.723 回答
11

有时,您可以使用正则表达式

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
于 2011-04-07T07:38:55.880 回答
9

你的代码不起作用;你需要or而不是||.

尝试

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

或者

strg[:1] in '0123456789'

或者,如果你真的很疯狂startswith

strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
于 2011-04-07T09:35:41.940 回答
4

这段代码:

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

打印出以下内容:

fukushima            False
123 is a number      True
                     False
于 2011-05-06T19:07:56.037 回答
2

您还可以使用try...except

try:
    int(string[0])
    # do your stuff
except:
    pass # or do your stuff
于 2017-07-26T16:42:47.543 回答
1

这是我的“答案”(试图在这里独一无二,我实际上并不推荐这种特殊情况:-)

使用ord()特殊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,是一个特殊的 Python 构造,它有点简洁:比较1 < 2 < 3(true) 和1 < 3 < 2(false) 和(1 < 3) < 2(true)。这不是它在大多数其他语言中的工作方式。)

使用正则表达式

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
于 2011-04-07T07:41:21.237 回答
1

使用内置字符串模块

>>> import string
>>> '30 or older'.startswith(tuple(string.digits))

接受的答案适用于单个字符串。我需要一种适用于pandas.Series.str.contains的方法。可以说比使用正则表达式更具可读性,并且很好地使用似乎并不为人所知的模块。

于 2022-02-24T13:09:53.840 回答
0

你可以使用正则表达式

您可以使用以下方法检测数字:

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

[0-9] par 匹配任何数字,yourstring[:1] 匹配字符串的第一个字符

于 2011-04-07T07:43:20.867 回答
-2

如果您打算以某种方式扩展方法的功能,请使用正则表达式。

于 2011-04-07T07:39:17.440 回答
-5

尝试这个:

if string[0] in range(10):
于 2011-04-07T07:35:55.720 回答