str.title() fails with words containing apostrophes

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Mon Mar 6 04:52:17 EST 2017


gvmcmt at gmail.com writes:

> On Monday, March 6, 2017 at 2:37:11 PM UTC+5:30, Jussi Piitulainen wrote:
>> gvmcmt at gmail.com writes:
>> 
>> > On Sunday, March 5, 2017 at 11:25:04 PM UTC+5:30, 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?
>> 
>> [snip sig]
>> 
>> > import string
>> >
>> > txt = "i can't be having with this"
>> > string.capwords(txt)
>> >
>> > That gives you "I Can't Be Having With This"
>> >
>> > Hope that helps.
>> 
>> Won't Steve D'aprano And D'arcy Cain Be Happy Now :)
>
>
> I found it at https://docs.python.org/3/library/string.html#string.capwords :)

Sure, it's there, and that's a good point. It still mangles their names.

It also mangles any whitespace in the string. That is probably mostly
harmless.

It also will capitalize all the little words in the string that are
usually not capitalized in titles, even in the usual headlinese English
variants. And all the acronyms and such that are usually written in all
caps, or in even odder patterns.

I guess it's a somewhat practical approximation to an AI-hard problem.
(Mumble mumble str.swapcase, er, never mind me :)


More information about the Python-list mailing list