在python中如何将UTF大写字符转换为小写字符

2024-10-01 07:20:31 发布

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

我想把大写字符串转换成小写字符串。在

例如,使用方法将字符串'LÄCHERLICH'转换为'lÄcherlich'

 str.lower()

Tags: 方法字符串lower小写大写strcherlich
3条回答

这应该做到:

# -*- 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

声明后转换:

^{pr2}$

它是哪个Python版本?在Python3中,使用lower()可以正确地转换它:

>>> x = 'LÄCHERLICH'
>>> print(x.lower())
lächerlich

对于python2,您应该使用unicode字符串(不要忘了在文件的开头定义编码):

^{pr2}$

相关问题 更多 >