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

发布于 2024-10-31 11:44:08 字数 432 浏览 4 评论 0原文

我有一个以数字开头的字符串(从 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

Is there a smarter/more effective way?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(12

格子衫的從容 2024-11-07 11:44:08

Python 的 string 库有 isdigit() 方法:

string[0].isdigit()

Python's string library has isdigit() method:

string[0].isdigit()
南城旧梦 2024-11-07 11:44:08
>>> string = '1abc'
>>> string[0].isdigit()
True
>>> string = '1abc'
>>> string[0].isdigit()
True
一曲琵琶半遮面シ 2024-11-07 11:44:08

令人惊讶的是,过了这么长时间,仍然没有找到最佳答案。

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

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

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

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

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
小耗子 2024-11-07 11:44:08

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

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

sometimes, you can use regex

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>
小镇女孩 2024-11-07 11:44:08

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

尝试

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

strg[:1] in '0123456789'

或,如果你真的很喜欢 startswith

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

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'))
瀞厅☆埖开 2024-11-07 11:44:08

这段代码:

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

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
〆凄凉。 2024-11-07 11:44:08

使用内置的 字符串模块

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

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

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. Arguably more readable than using a regular expression and a good use of a module that doesn't seem to be well-known.

童话里做英雄 2024-11-07 11:44:08

您还可以使用try... except

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

You can also use try...except:

try:
    int(string[0])
    # do your stuff
except:
    pass # or do your stuff
没有你我更好 2024-11-07 11:44:08

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

使用 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'

这个 a <; = b <= ca < b < c 一样,是一种特殊的 Python 结构,它很简洁:比较 1 < 2 < 3< /code> (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

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
め七分饶幸 2024-11-07 11:44:08

您可以使用正则表达式

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

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

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

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

乄_柒ぐ汐 2024-11-07 11:44:08

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

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

爱的故事 2024-11-07 11:44:08

试试这个:

if string[0] in range(10):

Try this:

if string[0] in range(10):
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文