2012-12-03 24 views
2

我使用這個代碼塊:如何將str.title與其他語言一起使用?

>>> 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的文檔。

如果字符串包括一個土耳其字符像「O」,字符串變成

「BOREK」。我應該寫什麼來支持所有語言?

回答

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 
+0

非常好。另外,我不想大寫一些像've'這樣的單詞。我如何添加這些單詞? – Burak

+0

@Burak你可以看看替代函數中的排除字典:'momaroup(0),如果mo.group(0)被排除在其他外...' – ecatmur

+0

非常感謝! – Burak

1

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

相關問題