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
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
If you want to match non-ASCII letters as well, you can use str.isalpha
:
if line and line[0].isalpha():
if line[0].isalpha():
–
Poohpooh 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.
An easy solution would be to use the python regex module:
import re
if re.match("^[a-zA-Z]+.*", line):
Do Something
[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 This is probably the most efficient method:
if line != "" and line[0].isalpha():
...
if line.startswith((chr(x) for x in range(ord('a'), ord('z')+1)+range(ord('A'), ord('Z')+1)):
# do processsing
pass
if you don't care about blanks in front of the string,
if line and line.lstrip()[0].isalpha():
© 2022 - 2024 — McMap. All rights reserved.
if line[:1].isalpha():
– Lanctot