Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python

How to use quopri.encodestring() in Python

Ayesha Naeem

The quopri.encodestring() function in Python performs quoted-printable encoding on data with few non-printable characters.

To use the quopri.encodestring() function, the program needs to import the quopri module as shown below:

import quopri

Prototype and parameters

  • The function accepts a byte source input as a non-optional parameter and returns the encoded bytes as the output.
  • The quotetabs parameter accepts a True or False value. The function encodes spaces and tabs if the quotetabs is True; otherwise, it leaves them unencoded.

Note: Tabs and spaces at the end of a line are always encoded.

  • The header parameter accepts a True or False value. The function decodes spaces as underscores if the header is True; otherwise, it leaves them unencoded.

Note: quopri.decodestring() uses False as the default value of header.

Explanation

The quopri.encodestring() function encodes all 8-bit value characters into a = and two hexadecimal digits, with the exception of printable ASCII characters. For example, = has a decimal value of 61 and is encoded as =3D.

All ASCII characters with decimal values from 33 to 126, except =, are printable and decoded as well as encoded as themselves.

A space with ASCII value 9 and a tab with ASCII value 32 represent themselves in the encoded data.

Examples

The following code demonstrates the use of the quopri.encodestring() function:

import quopri

#Example 1

#example text
text = 'This text contains ünicöde'

#create input
input1=text.encode('utf-8')

#Encode
output = quopri.encodestring(input1, quotetabs = False)

#get the output
print(output)

#Example 2

input2 = text.encode('utf-8')
output2 = quopri.encodestring(input2, quotetabs = True)
print(output2)

#Example 3

input3 = text.encode('utf-8')
output3 = quopri.encodestring(input3, quotetabs = False, header = True)
print(output3)

The example text contains two non-printable characters and three spaces.

Example 1

The quopri.encodestring() function takes the quotetabs parameter as False and displays the spaces as themselves as a result. The program encodes Unicode characters ü and ö as =C3=BC and =C3=B6 respectively.

Note: utf-8 encoding of Unicode characters can take up to four bytes.

Example 2

The quopri.encodestring() function takes the quotetabs parameter as False and encodes the spaces as =20 as a result.

Example 3

The quopri.encodestring() function takes the header parameter as True and encodes the spaces as _ as a result.

RELATED TAGS

python

CONTRIBUTOR

Ayesha Naeem
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring