patternpythonMinor
Extracting the first letter of a string
Viewed 0 times
thefirstextractingletterstring
Problem
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:
Do you think there is a better solution? Would
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?Solution
The only thing I can see is that you don't need to have the
Also, you could use
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), "")Context
StackExchange Code Review Q#141949, answer score: 4
Revisions (0)
No revisions yet.