When I was writing a search component today, I wanted to select the search field based on whether the search was for all letters.
So there is the following code:
if q.isalpha():
query = query.filter(User.username.ilike(like_str))else:
query = query.filter (User.realname.ilike(like_str))
But I found that even if there is Chinese in it, isalpha is judged to be true.
The test found that the method isalpha in str is unreliable in judging Unicode.
The default parameter decoding in Flask is UTF-8. Therefore, you need to use encode('utf-8') to re-encode it before Functionisalpha() can be used.
The test is as follows:
In [15]: u"张 x".isalpha() Out[15]: TrueIn [16]: "张 x".isalpha()Out[16]: False In [17]: "aac".isalpha() Out[17]: True In [18]: u"张 x".encode('utf-8').isalpha() Out[18]: False
[Related recommendations]
The above is the detailed content of isalpha does not support unicode in Python 2.7. For more information, please follow other related articles on the PHP Chinese website!