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
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
An easy solution would be to use the python regex module:
import re
if re.match("^[a-zA-Z]+.*", line):
Do Something
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.
This is probably the most efficient method:
if line != "" and line[0].isalpha():
...
If you want to match non-ASCII letters as well, you can do:
if line and line[0].isalpha():
if you don't care about blanks in front of the string,
if line and line.lstrip()[0].isalpha():