How to ASCII encode a string with error checking in Python

2 Answers

0 votes
s = "Python åäö"

es = s.encode(encoding="ASCII")

print(es)


'''
run:

UnicodeEncodeError: 'ascii' codec can't encode characters
                    in position 7-9: ordinal not in range(128)

'''

 



answered Dec 20, 2018 by avibootz
edited Dec 20, 2018 by avibootz
0 votes
s = "Python åäö"

print("1. ", s.encode(encoding="ASCII", errors="backslashreplace"))
print("2. ", s.encode(encoding="ASCII", errors="ignore"))
print("3. ", s.encode(encoding="ASCII", errors="namereplace"))
print("4. ", s.encode(encoding="ASCII", errors="replace"))
print("5. ", s.encode(encoding="ASCII", errors="xmlcharrefreplace"))
print("6. ", s.encode(encoding="ASCII", errors="strict"))


'''
run:

1.  b'Python \\xe5\\xe4\\xf6'

2.  b'Python '

3.  b'Python \\N{LATIN SMALL LETTER A WITH RING ABOVE}\\N{LATIN
    SMALL LETTER A WITH DIAERESIS}\\N{LATIN SMALL LETTER O WITH DIAERESIS}'

4.  b'Python ???'

5.  b'Python åäö'

Traceback (most recent call last):
  File "C:/Users/Avi/PycharmProjects/untitled/test.py", line 9, in <module>
    print("6. ", s.encode(encoding="ASCII", errors="strict"))
UnicodeEncodeError: 'ascii' codec can't encode characters in position 7-9:
                     ordinal not in range(128)

'''

 



answered Dec 20, 2018 by avibootz

Related questions

1 answer 135 views
1 answer 148 views
2 answers 173 views
1 answer 165 views
1 answer 165 views
...