[Python-ideas] Adding str.isascii() ?
Steven D'Aprano
steve at pearwood.info
Fri Jan 26 07:39:54 EST 2018
On Fri, Jan 26, 2018 at 05:42:31PM +0900, INADA Naoki wrote:
> If str has str.isascii() method, it can be simpler:
>
> `if s.isascii() and s.isdigit():`
>
> I want to add it in Python 3.7 if there are no opposite opinions.
I have no objection to isascii, but I don't think it goes far enough.
Sometimes I want to know whether a string is compatible with Latin-1 or
UCS-2 as well as ASCII. For that, I used a function that exposes the
size of code points in bits:
@property
def size(self):
# This can be implemented much more efficiently in CPython.
c = ord(max(self)) if self else 0
if c <= 0x7F:
return 7
elif c <= 0xFF:
return 8
elif c <= 0xFFFF:
return 16
else:
assert c <= 0x10FFFF
return 21
A quick test for ASCII will be:
string.size == 7
and to test that it is entirely within the BMP (Basic Multilingual
Plane):
string.size <= 16
--
Steve
More information about the Python-ideas
mailing list