Search code examples
pythonstringutf-8charactercapitalize

Capitalize doesn't work on special characters - Python


I've been trying to capitalize loads of strings, and some of them start with utf-8 characters. Problem is, they don't capitalize!

mystring = 'lucas'
mystring.capitalize() # returns 'Lucas'

mytring = 'æthelred'
mystring.capitalize() # returns 'æthelred'

Same with vowels containing `´^¨ and the characters ð, þ, e.t.c. What do I do to solve this?

I actually don't have access to the string, I get them somewhere else, in a text file...


Solution

  • You omit u . the string needs to be defined as unicode for python !

    >>> mytring = u"æthelred"
    >>> print mytring.capitalize()
    Æthelred
    

    As in python 3 strings are unicode by default you dont need u .

    >>> "æthelred".capitalize()
    'Æthelred'