Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: startswith any alpha character

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
like image 345
teggy Avatar asked Sep 01 '25 05:09

teggy


2 Answers

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

if line and line[0].isalpha():
like image 188
dan04 Avatar answered Sep 02 '25 18:09

dan04


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.

like image 37
efotinis Avatar answered Sep 02 '25 19:09

efotinis