isalpha does not support unicode in Python 2.7

Y2J
Release: 2017-05-18 15:07:33
Original
1691 people have browsed it

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
Copy after login

[Related recommendations]

1. Python free video tutorial

2. Check characters in python Method to determine whether a string is composed of letters: string.isalpha()

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!