如何使用 startswith 函数匹配任何字母字符 [a-zA-Z]。例如,我想这样做:
if line.startswith(ALPHA):
Do Something
如何使用 startswith 函数匹配任何字母字符 [a-zA-Z]。例如,我想这样做:
if line.startswith(ALPHA):
Do Something
如果你也想匹配非 ASCII 字母,你可以使用str.isalpha
:
if line and line[0].isalpha():
您可以将元组传递给startswiths()
(在 Python 2.5+ 中)以匹配其任何元素:
import string
ALPHA = string.ascii_letters
if line.startswith(tuple(ALPHA)):
pass
当然,对于这种简单的情况,正则表达式测试或in
运算符会更具可读性。
一个简单的解决方案是使用 python regex 模块:
import re
if re.match("^[a-zA-Z]+.*", line):
Do Something
这可能是最有效的方法:
if line != "" and line[0].isalpha():
...
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 and line.lstrip()[0].isalpha():