str.title() fails with words containing apostrophes
Terry Reedy
tjreedy at udel.edu
Sun Mar 5 15:40:58 EST 2017
On 3/5/2017 2:38 PM, MRAB wrote:
> 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())
Nice. It lowercases a word char that follows an "'" that follows a word
without an intervening non-word char. It passes this test:
print(title("'time' isn't 'timeless'!"))
'Time' Isn't 'Timeless'!
It guess the reason not to bake this exception into str.title is that it
is language specific and could even be wrong if someone used "'" to
separate words (perhaps in a different alphabet).
--
Terry Jan Reedy
More information about the Python-list
mailing list