[英]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我有一个以数字开头的字符串(从 0-9)我知道我可以使用 startswith() “或”10 个测试用例,但可能有一个更简洁的解决方案
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?有没有更聪明/更有效的方法?
Python's string
library has isdigit()
method: Python 的string
库有isdigit()
方法:
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.其他答案的缺点是使用[0]
选择第一个字符,但如前所述,这会在空字符串上中断。
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
sometimes, you can use regex有时,您可以使用正则表达式
>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
Your code won't work;您的代码将无法运行; you need or
instead of ||
你需要or
代替||
. .
Try尝试
'0' <= strg[:1] <= '9'
or要么
strg[:1] in '0123456789'
or, if you are really crazy about startswith
,或者,如果你真的很喜欢startswith
,
strg.startswith(('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'))
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
You can also use try...except
:您还可以使用try...except
:
try:
int(string[0])
# do your stuff
except:
pass # or do your stuff
Using the built-in string module :使用内置的字符串模块:
>>> import string
>>> '30 or older'.startswith(tuple(string.digits))
The accepted answer works well for single strings.接受的答案适用于单个字符串。 I needed a way that works with pandas.Series.str.contains .我需要一种适用于pandas.Series.str.contains的方法。 Arguably more readable than using a regular expression and a good use of a module that doesn't seem to be well-known.可以说比使用正则表达式更具可读性,并且很好地使用了一个似乎并不为人所知的模块。
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:特殊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 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.) (这个a <= b <= c
,就像a < b < c
一样,是一个特殊的 Python 结构,它有点简洁:比较1 < 2 < 3
(true) and 1 < 3 < 2
(false) and (1 < 3) < 2
(正确)。这不是大多数其他语言的工作方式。)
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
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 [0-9] par 匹配任意数字,yourstring[:1] 匹配字符串的第一个字符
Use Regular Expressions , if you are going to somehow extend method's functionality.如果您要以某种方式扩展方法的功能,请使用正则表达式。
Try this:试试这个:
if string[0] in range(10):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.