Python:以任何字母字符开头

发布于 2024-08-24 07:53:11 字数 119 浏览 8 评论 0原文

如何使用startswith函数来匹配任何字母字符[a-zA-Z]。例如我想这样做:

if line.startswith(ALPHA):
    Do Something

How can I use the startswith function to match any alpha character [a-zA-Z]. For example I would like to do this:

if line.startswith(ALPHA):
    Do Something

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

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

发布评论

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

评论(6

挽手叙旧 2024-08-31 07:53:11

如果您还想匹配非 ASCII 字母,可以使用 str .isalpha

if line and line[0].isalpha():

If you want to match non-ASCII letters as well, you can use str.isalpha:

if line and line[0].isalpha():
终遇你 2024-08-31 07:53:11

您可以将元组传递给 startswiths() (在 Python 2.5+ 中)以匹配其任何元素:

import string
ALPHA = string.ascii_letters
if line.startswith(tuple(ALPHA)):
    pass

当然,对于这个简单的情况,可以使用正则表达式测试或 in运算符将更具可读性。

You can pass a tuple to startswiths() (in Python 2.5+) to match any of its elements:

import string
ALPHA = string.ascii_letters
if line.startswith(tuple(ALPHA)):
    pass

Of course, for this simple case, a regex test or the in operator would be more readable.

心安伴我暖 2024-08-31 07:53:11

一个简单的解决方案是使用 python regex 模块:

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something

An easy solution would be to use the python regex module:

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something
你又不是我 2024-08-31 07:53:11

这可能是最有效的方法:

if line != "" and line[0].isalpha():
    ...

This is probably the most efficient method:

if line != "" and line[0].isalpha():
    ...
后知后觉 2024-08-31 07:53:11
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
    # do processsing
    pass
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
    # do processsing
    pass
dawn曙光 2024-08-31 07:53:11

如果你不关心字符串前面的空格,

if line and line.lstrip()[0].isalpha(): 

if you don't care about blanks in front of the string,

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