cStringIO vs StringIO when using write unicode

28 views
Skip to first unread message

Lei Zhang

unread,
Nov 24, 2013, 10:43:44 PM11/24/13
to pyth...@googlegroups.com
使用这两个包时,出现如下问题,谁能给解释下method?
 

```
In [15]: StringIO.StringIO().write(u'\u2222')

In [16]: cStringIO.StringIO().write(u'\u2222')
---------------------------------------------------------------------------
UnicodeEncodeError                        Traceback (most recent call last)
<ipython-input-16-a7a28c8bfb39> in <module>()
----> 1 cStringIO.StringIO().write(u'\u2222')

UnicodeEncodeError: 'ascii' codec can't encode character u'\u2222' in position 0: ordinal not in range(128)
```

--
Lei Zhang
twitter/weibo: @jeffrey4l

Hsiaoming Yang

unread,
Nov 24, 2013, 11:03:52 PM11/24/13
to pyth...@googlegroups.com

Unlike the StringIO module, this module is not able to accept Unicode strings that cannot be encoded as plain ASCII strings.

Leo Jay

unread,
Nov 24, 2013, 11:10:59 PM11/24/13
to python-cn:CPyUG
2013/11/25 Lei Zhang <zhang....@gmail.com>:
> 使用这两个包时,出现如下问题,谁能给解释下method?
>
>
> ```
> In [15]: StringIO.StringIO().write(u'\u2222')
>
> In [16]: cStringIO.StringIO().write(u'\u2222')
> ---------------------------------------------------------------------------
> UnicodeEncodeError Traceback (most recent call last)
> <ipython-input-16-a7a28c8bfb39> in <module>()
> ----> 1 cStringIO.StringIO().write(u'\u2222')
>
> UnicodeEncodeError: 'ascii' codec can't encode character u'\u2222' in
> position 0: ordinal not in range(128)
> ```
>

不要在输出的时候,直接写unicode。
自己显式的转成某种编码,然后再写。

> --
> Lei Zhang
> Blog: http://xcodest.me
> twitter/weibo: @jeffrey4l
>

--
Best Regards,
Leo Jay

est

unread,
Nov 24, 2013, 11:11:57 PM11/24/13
to pyth...@googlegroups.com
你传一个 u'' 进去,内部实现就是个简单粗暴的 str(u'') 当然会出错。


2013/11/25 Lei Zhang <zhang....@gmail.com>

--
--
邮件来自: `CPyUG`华蟒用户组(中文Python技术邮件列表)
规则: http://code.google.com/p/cpyug/wiki/PythonCn
发言: pyth...@googlegroups.com
详情: http://code.google.com/p/cpyug/wiki/CpyUg
G+: https://plus.google.com/u/0/communities/108786798869709602787
严正: 理解列表! 智慧提问! http://wiki.woodpecker.org.cn/moin/AskForHelp
---
您收到此邮件是因为您订阅了 Google 网上论坛的“python-cn(华蟒用户组,CPyUG 邮件列表)”论坛。
要退订此论坛并停止接收此论坛的电子邮件,请发送电子邮件到 python-cn+...@googlegroups.com
要查看更多选项,请访问 https://groups.google.com/groups/opt_out。

Lei Zhang

unread,
Nov 24, 2013, 11:14:40 PM11/24/13
to pyth...@googlegroups.com
了解了,看文档不仔细啊.
只是想知道为啥这两个的处理会有不同.


2013/11/25 est <electr...@gmail.com>

limodou

unread,
Nov 25, 2013, 12:08:18 AM11/25/13
to Python.cn@google
cStringIO是用C写的,没做成unicode支持的,所以要转为str才可以。


2013/11/25 Lei Zhang <zhang....@gmail.com>



--
I like python!
UliPad <<The Python Editor>>: http://code.google.com/p/ulipad/
UliWeb <<simple web framework>>: https://github.com/limodou/uliweb
My Blog: http://my.oschina.net/limodou
Reply all
Reply to author
Forward
0 new messages