如何将str.title与其他语言一起使用?

时间:2012-12-03 10:17:23

标签: python

我正在使用此代码块:

>>> import re
>>> def titlecase(s):
...     return re.sub(r"[A-Za-z]+('[A-Za-z]+)?",
...                   lambda mo: mo.group(0)[0].upper() +
...                              mo.group(0)[1:].lower(),
...                   s)
...
>>> titlecase("they're bill's friends.")
"They're Bill's Friends."

这是来自Python的文档。

如果字符串包含像'ö'这样的土耳其字符,则字符串变为

'BOREK'。我应该写什么才能支持所有语言?

2 个答案:

答案 0 :(得分:2)

使用Unicode字符属性数据库,通过使用flags=re.UNICODE编译正则表达式:

def titlecase(s):
    return re.sub(re.compile(r"[\w]+('[\w]+)?", flags=re.UNICODE),
                  lambda mo: mo.group(0)[0].upper() +
                             mo.group(0)[1:].lower(),
                  s)

在Python 2上,您需要使用Unicode字符串:

>>> print titlecase(u"börek")
Börek

答案 1 :(得分:1)

使用unicode字符串,即titlecase(u'börek')

相关问题