Python string encode














































Python string encode



Python String : encode()


This article demonstrates how to use of encode() method in string.

The string encode() method returns encoded version of the given string.

Since Python 3.0, strings are stored as Unicode, i.e. each character in the string is represented by a code point. So, each string is just a sequence of Unicode code points.

For efficient storage of these strings, the sequence of code points are converted into set of bytes. The process is known as encoding.

There are various encodings present which treats a string differently. The popular encodings being utf-8ascii, etc.

Using string's encode() method, you can convert unicoded strings into any encoding supported by python . By default, Python uses utf-8 encoding.


Syntax :

string.encode(encoding='UTF-8',errors='strict')


Parameter Values :

By default, encode() method doesn't require any parameters.

It returns utf-8 encoded version of the string. In case of failure, it raises a UnicodeDecodeError exception.

However, it takes two parameters:

  • encoding - the encoding type a string has to be encoded to
  • errors - response when encoding fails. There are six types of error response
    • strict - default response which raises a UnicodeDecodeError exception on failure
    • ignore - ignores the unencodable unicode from the result
    • replace - replaces the unencodable unicode to a question mark ?
    • xmlcharrefreplace - inserts XML character reference instead of unencodable unicode
    • backslashreplace - inserts a \uNNNN escape sequence instead of unencodable unicode
    • namereplace - inserts a \N{...} escape sequence instead of unencodable unicode


Returns :

returns encoded version of the given string.



Sample Code :
1.

 Encode to Default Utf-8 Encoding :

# unicode string
string = 'pyth%uFFFDn!'

# print string
print('The string is:', string)

# default encoding to utf-8
string_utf = string.encode()

# print result
print('The encoded version is:', string_utf)

Output :
The string is: pyth%uFFFDn!                                                                                                                        
The encoded version isb'pyth\xc3\xb6n!'


2.

Encoding with error parameter :

# unicode string
string = 'pyth%uFFFDn!'

# print string
print('The string is:', string)

# ignore error
print('The encoded version (with ignore) is:', string.encode("ascii""ignore"))

# replace error
print('The encoded version (with replace) is:', string.encode("ascii""replace"))
Output :
The string is: pyth%uFFFDn!                                                                                                                        
The encoded version (with ignore) isb'pythn!'                                                                                               
The encoded version (with replace) isb'pyth?n!'


Hence,we can see above that the encode() function returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'.


**********END OF ARTICLE **********


More Articles of Vishal Lodhi:

Name Views Likes
Python string zfill 115 0
Python string swapcase 93 0
Python string title 97 0
Python string startswith 103 0
Python string replace 144 0
Python string translate 85 0
Python string rpartition 86 0
Python string partition 74 0
Python string splitlines 114 0
Python string rsplit 79 0
Python string split 76 0
Python string rindex 82 0
Python string rfind 106 0
Python string upper 80 0
Python string lower 82 0
Python string maketrans 90 0
Python string strip 81 0
Python string rstrip 92 0
Python string lstrip 80 0
Python string rjust 97 0
Python string ljust 96 0
Python string len 82 0
Python string join 76 0
Python string casefold 82 0
Python string isprintable 85 0
Python string encode 79 0
Python string isdecimal 85 0
Python string isidentifier 78 0
Python string isupper 78 0
Python string istitle 80 0
Python string isspace 100 0
Python string isnumeric 102 0
Python string isdigit 83 0
Python string islower 85 0
Python string isalpha 96 0
Python string isalnum 102 0
Python string index 88 0
Python string find 94 0
Python string expandtabs() 81 0
Python string endswith 92 0
Python string count 86 0
Python string capitalize 78 0
Python string center 85 0
Python string Introduction 99 0
Python string Template 141 0
Python string Formatter 145 0
Python string printable 199 0
Python string whitespace 146 0
Python string punctuation 104 0
Python string octdigits 87 0
Python string hexdigits 104 0
Python string digits 80 0
Python string ascii_letters 344 0
Python string ascii_lowercase 147 0
Python string ascii_uppercase 157 0
How to Create Download Manager in Python 524 0
Python random weibullvariate 165 0
python random paretovariate 135 0
Python random vonmisesvariate 178 0
Python random normalvariate 196 0
Python random lognormvariate 120 0
Python random gauss 120 0
Python random gammavariate 131 0
Python random expovariate 194 0
Python random betavariate 186 0
Python random triangular 117 0
Python random uniform 141 0
Python random random 117 0
Python random sample 183 0
Python random shuffle 179 0
Python random choices 234 0
Python random choice 166 0
Python random randint 149 0
Python random randrange 214 0
Python random getrandbits 141 0
Python random setstate 137 0
Python random getstate 178 0
Python random seed 168 1
Python random Introduction 175 0

Comments