How do I case fold a string in Python 2?

时光总嘲笑我的痴心妄想 提交于 2019-12-29 05:20:53

问题


Python 3.3 adds the casefold method to the str type, but in 2.x I don't have anything. What's the best way to work around this?


回答1:


Check out py2casefold.

>>> from py2casefold import casefold
>>> print casefold(u"tschüß")
tschüss
>>> casefold(u"ΣίσυφοςfiÆ") == casefold(u"ΣΊΣΥΦΟσFIæ") == u"σίσυφοσfiæ"
True



回答2:


There is a thread here which covers some of the issues (but may not resolve all), you can judge whether it is suitable for what you need. If this is no good then there are some useful tips for implementing case folding on the W3C site here.




回答3:


If PyICU is already installed; you could use it to define casefold(). Using the same example strings as in @Russ' answer:

>>> import icu
>>> casefold = lambda u: unicode(icu.UnicodeString(u).foldCase())
>>> print casefold(u"tschüß")
tschüss
>>> casefold(u"ΣίσυφοςfiÆ") == casefold(u"ΣΊΣΥΦΟσFIæ") == u"σίσυφοσfiæ"
True
>>> icu.UNICODE_VERSION
'6.3'
>>> import unicodedata
>>> unicodedata.unidata_version
'5.2.0'

The result may depend on the version of Unicode standard.



来源:https://stackoverflow.com/questions/18271077/how-do-i-case-fold-a-string-in-python-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!