如果字符串包含德语变音符号 (üöä),则 Python string.title() 函数会出现奇怪的行为。然后,不仅字符串的第一个字符大写,元音后面的字符也大写。

# -*- coding: utf-8 -*-
a = "müller"
print a.title()
# this returns >MüLler< , not >Müller< as expected

试图通过将语言环境设置为德语 UTF-8 字符集来修复,但没有成功:
import locale
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
a="müller"
print a.title()
# same value >MüLler<

有什么想法可以防止变音后的大写?
我的 Python 版本在 debian linux 上是 2.6.6

最佳答案

将您的字符串解码为 Unicode,然后使用 unicode.title() :

>>> a = "müller"
>>> a.decode('utf8').title()
u'M\xfcller'
>>> print a.decode('utf8').title()
Müller

以后您始终可以再次编码为 UTF-8。

关于德语变音的 Python string.title() 问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31677925/

10-12 15:53