Python string encode method

Encode a string

We can use encode method from string class to encode a string. The following code encodes a string in 'utf-8'.


uniStr = u"Ni\u00F1o"
print uniStr.encode('utf-8')

The code above generates the following result.

Encode in 'utf-16'.


uniStr = u"Ni\u00F1o"
print uniStr.encode('utf-16')

The code above generates the following result.

Encode in 'iso-8859-1'


locStr = "El "
uniStr = u"Ni\u00F1o"
newStr = locStr+uniStr
print newStr.encode('iso-8859-1')

The code above generates the following result.

Encode in 'latin-1'


s = u'La Pe\xf1a'                         
print s                                        
print s.encode('latin-1')

The code above generates the following result.





















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary