2

My code:

def check_string(text):

    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))

    return text if valid else ""

While I process some text, I got the following error:

File "/data/text_normalizer.py", line 176, in check_string
    valid = bool(text and (not text.isascii() or any(t.isalnum() for t in text)))
AttributeError: 'str' object has no attribute 'isascii'

isascii() is indeed a function of a str object, so why does it report this error?

marlon
  • 6,029
  • 8
  • 42
  • 76
  • 2
    `isascii` was added in Python 3.7, are you perhaps running an older version? – 0x5453 Feb 09 '22 at 22:20
  • 1
    Oh, yes. it's python 3.6.9. Is there an equivalent one in 3.6.9? – marlon Feb 09 '22 at 22:22
  • You can use the `string` library and compare the characters. I think it’s `string.ascii_letters` and `string.digits`. Perhaps `string.printable` *might* suit your case? – S3DEV Feb 09 '22 at 22:29

1 Answers1

3

isascii requires Python 3.7 or later.

vjh
  • 115
  • 3
  • Is this the same? "return all(ord(c) < 128 for c in text)" – marlon Feb 09 '22 at 22:29
  • That seems as though it would work as well. Perhaps crack into the source code for the `isascii` method to verify. [From the docs](https://docs.python.org/3/library/stdtypes.html?highlight=split#str.isascii): “Return True if the string is empty or all characters in the string are ASCII, False otherwise. ASCII characters have code points in the range U+0000-U+007F.” – S3DEV Feb 09 '22 at 22:31