28

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
teggy
  • 5,995
  • 9
  • 38
  • 41

6 Answers6

61

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

if line and line[0].isalpha():
Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
dan04
  • 87,747
  • 23
  • 163
  • 198
13

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
  • 14,565
  • 6
  • 31
  • 36
  • I did not know that. +1 not for the best answer for this question, but because that is by far the best answer for a ton of my own code. Thank you. – DaveTheScientist May 09 '12 at 21:27
9

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

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something
Il-Bhima
  • 10,744
  • 1
  • 47
  • 51
  • -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 Mar 07 '10 at 10:12
  • 7
    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 Mar 07 '10 at 10:53
3

This is probably the most efficient method:

if line != "" and line[0].isalpha():
    ...
Dave Kirby
  • 25,806
  • 5
  • 67
  • 84
0
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
    # do processsing
    pass
shantanoo
  • 3,617
  • 1
  • 24
  • 37
-1

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

if line and line.lstrip()[0].isalpha(): 
ghostdog74
  • 327,991
  • 56
  • 259
  • 343