str.title() fails with words containing apostrophes

MRAB python at mrabarnett.plus.com
Sun Mar 5 14:38:54 EST 2017


On 2017-03-05 17:54, Steve D'Aprano wrote:
> I'm trying to convert strings to Title Case, but getting ugly results if the
> words contain an apostrophe:
>
>
> py> 'hello world'.title()  # okay
> 'Hello World'
> py> "i can't be having with this".title()  # not okay
> "I Can'T Be Having With This"
>
>
> Anyone have any suggestions for working around this?
>
A bit of regex?

import re

def title(string):
     return re.sub(r"\b'\w", lambda m: m.group().lower(), string.title())




More information about the Python-list mailing list