views:

343

answers:

5

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
A: 

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

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something
Il-Bhima
-1: Using regex is massively overkill for this task. Also you only need to check the first character - this regex will try and match the whole string, which could be very long.
Dave Kirby
Even if you were forced to use the re module, all you needed was `[a-zA-Z]`. The `^` is a waste of a keystroke (read the docs section about the difference between `search` and `match`). The `+` is a minor waste of time (major if the string has many letters at the start); one letter is enough. The `.*` is a waste of 2 keystrokes and possibly a lot more time.
John Machin
A: 

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.

efotinis
+3  A: 

This is probably the most efficient method:

if line != "" and line[0].isalpha():
    ...
Dave Kirby
+1, This is the best solution, especially if wrapped in a function or even a method of some validation class.
Carson Myers
Why do you think that this is better than `if line and line[0].isalpha():`?
John Machin
+10  A: 

If you want to match non-ASCII letters as well, you can do:

if line and line[0].isalpha():
dan04
+1, This is the best solution, especially if wrapped in a function or even a method of some validation class.
Anurag Uniyal
of course, line must be a unicode object for the non-Ascii part to work.
kaizer.se
Even shorter: `if line[:1].isalpha():`
Will Hardy
@Will What is the difference between your answer and `if line[0].isalpha():`
teggy
@teggy: The difference is that if line is an empty string, line[:1] will evaluate to an empty string while line[0] will raise an IndexError.
dan04
A: 

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

if line and line.lstrip()[0].isalpha(): 
ghostdog74
and if you don't care about exceptions ... `>>> line = " \n"` `>>> line and line.lstrip()[0].isalpha()` `Traceback (most recent call last):` ` File "<stdin>", line 1, in <module>` `IndexError: string index out of range`
John Machin