Strings and Unicode

Gerhard Häring gh at ghaering.de
Sun Jul 20 15:14:37 CEST 2003


An AC wrote:
> I have a function that takes a string as an input parameter. This
> function then urlencodes the string and sends it to a server with
> telnetlib.Telnet
> 
> The problem is that the string gets converted into what seems to be
> Unicode. How can I check to see if the input-string is Unicode and
> convert it to a different character set (in this case ISO-Latin1).

Either:

if type(s) is unicode:
     s = s.encode("latin1")

or:

if isinstance(s, unicode):
     s = s.encode("latin1")

if you want to be prepared for subclasses of unicode strings. I prefer 
the first version because of its efficiency. In the very rare case that 
any string or unicode subclasses appear I can switch to the second 
version later on.

-- Gerhard





More information about the Python-list mailing list