[IronPython] How to convert a unicode variable to string?

Curt Hagenlocher curt at hagenlocher.org
Tue Sep 23 17:15:41 CEST 2008


IronPython wants to treat this string as Unicode because it's got a
character with the high bit set.  You can actually get an equivalent result
from CPython when you tell it to use Unicode:

>>> a="Pitón"
>>> str(a)
'Pit\xa2n'
>>> a=u"Pitón"
>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf3' in position
3: ordinal not in range(128)
>>>

(Though I can't help but notice that we may be raising the wrong type of
error.)

You'll probably need to special-case unicode strings and keep them as
unicode instead of trying to convert them with "str" to a single-byte
string.

On Tue, Sep 23, 2008 at 6:52 AM, Vizcayno <vizcaynot at gmail.com> wrote:

> Hello:
> Is there a workaround to solve the next problem?
>
> .ipy
> IronPython 2.0 Beta (2.0.0.5000) on .NET 2.0.50727.3053
> Type "help", "copyright", "credits" or "license" for more information.
> >>> a="Pitón"
> >>> print str(a)
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "mscorlib", line unknown, in GetString
>  File "mscorlib", line unknown, in GetChars
>  File "mscorlib", line unknown, in Fallback
>  File "mscorlib", line unknown, in Throw
> UnicodeDecodeError: ('unknown', u'\xf3', 3, 4, '')
> >>>
>
>
> I python 2.5 I get:
> >>> a = "Pitón"
> >>> print str(a)
> Pitón
> >>>
>
> May be you will ask: why to do that? well,  what I want is to convert
> any value a variable receives (float, unicode, int, string, etc) to a
> string variable.
> Many thanks for your time and help.
> Vizcayno.
> _______________________________________________
> Users mailing list
> Users at lists.ironpython.com
> http://lists.ironpython.com/listinfo.cgi/users-ironpython.com
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/ironpython-users/attachments/20080923/bc1cd412/attachment.html>


More information about the Ironpython-users mailing list