Python: startswith any alpha character
59,951
Solution 1
If you want to match non-ASCII letters as well, you can use str.isalpha
:
if line and line[0].isalpha():
Solution 2
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.
Solution 3
An easy solution would be to use the python regex module:
import re
if re.match("^[a-zA-Z]+.*", line):
Do Something
Solution 4
This is probably the most efficient method:
if line != "" and line[0].isalpha():
...
Related videos on Youtube
Author by
teggy
Updated on July 09, 2022Comments
-
teggy almost 2 years
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
-
Dave Kirby about 14 years-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.
-
John Machin about 14 yearsEven 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 betweensearch
andmatch
). 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. -
Will Hardy about 14 yearsEven shorter:
if line[:1].isalpha():
-
teggy about 14 years@Will What is the difference between your answer and
if line[0].isalpha():
-
dan04 about 14 years@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.
-
DaveTheScientist about 12 yearsI 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.