python设置utf-8,在Python中使用UTF-8

As it is summer now, I decided to learn a new language and Python was my choice. Really, what I would like to learn is how to manipulate Arabic text using Python. Now, I have found many many resources on using Python, which are really great. However, when I apply what I learned on Arabic strings, I get numbers and letters combined together.

Take for example this for English:

>>> ebook = 'The American English Dictionary'

>>> ebook[2]

'e'

Now, for Arabic:

>>> abook = 'القاموس العربي'

>>> abook[2]

'\xde' #the correct output should be 'ق'

However, using print works fine, as in:

>>> print abook[2]

ق

What do I need to modify to get Python to always recognize Arabic letters?

解决方案

Use Unicode explicitly:

>>> s = u'القاموس العربي'

>>> s

u'\u0627\u0644\u0642\u0627\u0645\u0648\u0633 \u0627\u0644\u0639\u0631\u0628\u064a'

>>> print s

القاموس العربي

>>> print s[2]

ق

Or even character by character:

>>> for i, c in enumerate(s):

... print i,c

...

0 ا

1 ل

2 ق

3 ا

4 م

5 و

6 س

7

8 ا

9 ل

10 ع

11 ر

12 ب

13 ي

14

I recommend the Python Unicode page which is short, practical and useful.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值