Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,924 questions

51,857 answers

573 users

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 116 views
1 answer 129 views
2 answers 160 views
1 answer 152 views
1 answer 150 views
...