Python: startswith any alpha character
Asked Answered
P

6

31

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
Poohpooh answered 7/3, 2010 at 9:49 Comment(0)
A
62

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

if line and line[0].isalpha():
Aloes answered 7/3, 2010 at 10:8 Comment(3)
Even shorter: if line[:1].isalpha():Lanctot
@Will What is the difference between your answer and if line[0].isalpha():Poohpooh
@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.Aloes
C
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.

Cortese answered 7/3, 2010 at 10:3 Comment(1)
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.Trefoil
S
9

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

import re
if re.match("^[a-zA-Z]+.*", line):
   Do Something
Superintendency answered 7/3, 2010 at 9:56 Comment(2)
-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.Froissart
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.Mountaineering
F
3

This is probably the most efficient method:

if line != "" and line[0].isalpha():
    ...
Froissart answered 7/3, 2010 at 10:8 Comment(0)
B
0
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
    # do processsing
    pass
Bankhead answered 9/9, 2011 at 19:37 Comment(0)
C
-1

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

if line and line.lstrip()[0].isalpha(): 
Coition answered 7/3, 2010 at 11:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.