How to use quopri.encodestring() in Python
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
inputas a non-optional parameter and returns the encoded bytes as theoutput. - The
quotetabsparameter accepts aTrueorFalsevalue. The function encodes spaces and tabs if thequotetabsisTrue; otherwise, it leaves them unencoded.
Note: Tabs and spaces at the end of a line are always encoded.
- The
headerparameter accepts aTrueorFalsevalue. The function decodes spaces as underscores if theheaderisTrue; otherwise, it leaves them unencoded.
Note:
quopri.decodestring()usesFalseas the default value ofheader.
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 texttext = 'This text contains ünicöde'#create inputinput1=text.encode('utf-8')#Encodeoutput = quopri.encodestring(input1, quotetabs = False)#get the outputprint(output)#Example 2input2 = text.encode('utf-8')output2 = quopri.encodestring(input2, quotetabs = True)print(output2)#Example 3input3 = 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-8encoding 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.
Free Resources