我希望把大写字符串转换成小写字符串。
例如,使用该方法将字符串'LÄCHERLICH'
转换为'lÄcherlich'
。
str.lower()
我希望把大写字符串转换成小写字符串。
例如,使用该方法将字符串'LÄCHERLICH'
转换为'lÄcherlich'
。
str.lower()
这是哪个Python版本?在Python 3中,使用lower()
可以正确转换:
>>> x = 'LÄCHERLICH'
>>> print(x.lower())
lächerlich
对于 Python 2,您应该使用 Unicode 字符串(并不要忘记在文件开头定义编码):
# coding: utf-8
x = u'LÄCHERLICH'
print x.lower().encode('utf8')
这应该可以:
# -*- coding: utf-8 -*-
a = 'LÄCHERLICH'
print a.decode('utf8').lower()
decode
将会像你想在 u'LÄCHERLICH'
上使用 lower()
一样工作。
针对Python 2.7版本
问题在于,当您声明字符串时,它会将其视为ASCII字符集。因此,在声明或之后定义为UTF字符集是必要的。
In [17]: str = 'LÄCHERLICH' # didn't specify encoding(so ASCII by default)
In [18]: print str.lower()
lÄcherlich
In [19]: str = u'LÄCHERLICH' #declaring that it's UTF
In [20]: print str.lower()
lächerlich
在声明后进行转换:
In [21]: str = 'LÄCHERLICH'
In [22]: print str.decode('utf8').lower()
lächerlich