I want to I check whether a string is in ASCII or not.
I am aware of ord()
, however when I try ord('é')
, I have TypeError: ord() expected a character, but string of length 2 found
. I understood it is caused by the way I built Python (as explained in ord()
's documentation).
Is there another way to check?
To improve Alexander's solution from the Python 2.6 (and in Python 3.x) you can use helper module curses.ascii and use curses.ascii.isascii() function or various other: https://docs.python.org/2.6/library/curses.ascii.html
To prevent your code from crashes, you maybe want to use a
try-except
to catchTypeErrors
For example
Python 3 way:
New in Python 3.7 (bpo32677)
No more tiresome/inefficient ascii checks on strings, new built-in
str
/bytes
/bytearray
method -.isascii()
will check if the strings is ascii.I use the following to determine if the string is ascii or unicode:
Then just use a conditional block to define the function:
How about doing this?