26

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

if line.startswith(ALPHA):
    Do Something
4

6 回答 6

56

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

if line and line[0].isalpha():
于 2010-03-07T10:08:43.117 回答
13

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

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

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

于 2010-03-07T10:03:03.433 回答
8

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

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something
于 2010-03-07T09:56:30.873 回答
3

这可能是最有效的方法:

if line != "" and line[0].isalpha():
    ...
于 2010-03-07T10:08:35.573 回答
0
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
    # do processsing
    pass
于 2011-09-09T19:37:25.173 回答
-1

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

if line and line.lstrip()[0].isalpha(): 
于 2010-03-07T11:20:44.043 回答