2012-03-30 76 views
18

当我在Python 2.7中使用.lower()时,字符串不会被转换成小写字母ŠČŽ。 我从字典中读取数据。python 2.7小写

我试过使用str(tt["code"]).lower(),tt["code"].lower()

有什么建议吗?

+1

看看http://stackoverflow.com/questions/727507/how-can-i-do-unicode-uppercase,我想它可能是相关的。 – mgilson 2012-03-30 12:45:44

回答

22

使用Unicode字符串:

[email protected]:~$ python 
Python 2.7.2+ (default, Oct 4 2011, 20:06:09) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> print "ŠČŽ" 
ŠČŽ 
>>> print "ŠČŽ".lower() 
ŠČŽ 
>>> print u"ŠČŽ".lower() 
ščž 

见那个小u?这意味着它创建为unicode对象而不是str对象。

+2

但是,如果它不是一个文字,他如何得到unicode? – agf 2012-03-30 12:51:39

+0

我正在阅读字典,所以如何将tt [“code”]转换为u“ŠČŽ”? – Yebach 2012-03-30 13:07:31

+0

使用** unicode(tt [“code”],'latin2')**,其中'latin2'是使用的编码,因此您可能需要使用不同的编码。 – Tupteq 2012-03-30 13:31:32

4

使用Unicode:

>>> print u'ŠČŽ'.lower().encode('utf8') 
ščž 
>>> 

您需要将您的文本尽快UNICODE ,因为它从外界进入你的程序,而不是仅仅在转换点上,你会注意到一个问题。

因此,要么使用codecs模块读取解码文本,要么使用'bytestring'.decode('latin2')(其中latin2的位置应该使用任何实际的编码)。

+0

我正在阅读字典,所以如何将tt [“code”]转换为u“ŠČŽ”?我不能使用ustr(tt [“code”])。lower()。encode('utf8')或str(tt [u“code”])。lower()。encode('utf8') – Yebach 2012-03-30 13:14:27

+0

@Yebach查看更新。 – Marcin 2012-03-30 13:45:10