如何判断字符串是否以 Python 中的数字开头?

我有一个以数字开头的字符串(从0到9) 我知道我可以使用 startswith ()“或”10个测试用例,但是可能有一个更简洁的解决方案

所以不用写了

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

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

158208 次浏览

试试这个:

if string[0] in range(10):

Python 的 string库具有 isdigit()方法:

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

有时,您可以使用 regex

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

使用 正则表达式,如果你想以某种方式扩展方法的功能。

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

使用 Rel = “ nofollow”> ord () and特殊的 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'

(这个 a <= b <= ca < 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

你可以用 正则表达式

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

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

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

您的代码将无法工作; 您需要 or而不是 ||

试试看

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

或者

strg[:1] in '0123456789'

或者,如果你真的很喜欢 startswith,

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

这段代码:

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

你也可以使用 try...except:

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

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

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

使用下面的方法可以避免这个问题,并且,在我看来,给出了我们所拥有的选项的最漂亮和最可读的语法。它也不会导入/干扰正则表达式) :

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


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

使用内置的 字符串模块:

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

对于单个字符串,可接受的答案工作得很好。我需要一种与 熊猫协同工作的方法。可以说比使用正则表达式和充分利用一个似乎并不广为人知的模块更具可读性。