str.title() fails with words containing apostrophes

gvmcmt at gmail.com gvmcmt at gmail.com
Mon Mar 6 04:17:35 EST 2017


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?
> 
> 
> 
> -- 
> Steve
> “Cheer up,” they said, “things could be worse.” So I cheered up, and sure
> enough, things got worse.

import string 

txt = "i can't be having with this" 
string.capwords(txt) 

That gives you "I Can't Be Having With This" 

Alternatively

txt = "i can't be having with this"

' '.join([word.capitalize() for word in txt.split()])

will result in: "I Can't Be Having With This"


More information about the Python-list mailing list