Check that a string contains only ASCII characters?

后端 未结 4 1804
执笔经年
执笔经年 2020-12-29 09:27

How do I check that a string only contains ASCII characters in Python? Something like Ruby\'s ascii_only?

I want to be able to tell whether string speci

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-29 10:23

    A workaround to your problem would be to try and encode the string in a particular encoding.

    For example:

    'H€llø'.encode('utf-8')
    

    This will throw the following error:

    Traceback (most recent call last):
        File "", line 1, in 
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 1: ordinal not in range(128)
    

    Now you can catch the "UnicodeDecodeError" to determine that the string did not contain just the ASCII characters.

    try:
        'H€llø'.encode('utf-8')
    except UnicodeDecodeError:
        print 'This string contains more than just the ASCII characters.'
    

提交回复
热议问题