# Extracting the first letter of a string

I'm extracting the first letter (not symbol) of a string using Unicode characters, with French words/sentences in mind.

I have implemented it like this:

def lettrine(text):
first = next((c for c in text if c.isalpha()), "")
return first

assert lettrine(u":-)") == u""
assert lettrine(u"Éléphant") == u"É"
assert lettrine(u"\u03b1") == u"α"
assert lettrine(u":-)") == u""
assert lettrine(u"") == u""


Do you think there is a better solution? Would isalpha work just as well on both Python 2.7 and 3.5?

The only thing I can see is that you don't need to have the return on a separate line. return next((c for c in text if c.isalpha()), "") works fine. It works on both python 2 and python 3 from what I can see.

Also, you could use filter in this situation: return next(iter(filter(unicode.isalpha, text)), ""), although I am not sure that is any real improvement. On python 3 this approach is a bit simpler: return next(filter(str.isalpha, text), "")

According to the Python 3.5 documentation, isalpha function return True if all characters are letters:

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

The Python 2.7 documentaion needs improvement (it is not clear with unicode.isalpha): isalpha works the same way:

$python --version Python 2.7.10$ python -c 'print u"\u03b1".isalpha()'
True


So, this function can extract the first letter of a unicode strings:

def lettrine(text):
return next((c for c in text if c.isalpha()), "")