python 2.7小写

2024-04-25 00:00:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试着用str(tt["code"]).lower()tt["code"].lower()

有什么建议吗?


Tags: 字符串字典codelower建议ttstr读数据
2条回答

使用unicode:

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

当文本从外部世界进入程序时,您需要将其转换为unicode,而不仅仅是在您注意到问题的时候。

因此,要么使用codecs模块读取解码文本,要么使用'bytestring'.decode('latin2')(在这里,您应该使用实际的编码来代替latin2)。

使用unicode字符串:

drostie@signy:~$ 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()
ščž

看到那一点了吗?这意味着它是作为unicode对象而不是str对象创建的。

相关问题 更多 >