2012-03-30 80 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