str.title() fails with words containing apostrophes
Peter Otten
__peter__ at web.de
Mon Mar 6 05:04:48 EST 2017
More information about the Python-list mailing list
Mon Mar 6 05:04:48 EST 2017
- Previous message (by thread): str.title() fails with words containing apostrophes
- Next message (by thread): str.title() fails with words containing apostrophes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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 :) Perhaps one could limit the conversion to go from lower to upper only, as names tend be in the desired case in the original text. >>> def first_up(s): ... return s[:1].upper() + s[1:] ... >>> def title(s): ... return re.compile(r"(?:\b'?)\w+").sub(lambda m: first_up(m.group()), s) ... >>> title("won't steve D'Aprano and d'arcy cain be 'happy' now?") "Won't Steve D'Aprano And D'arcy Cain Be 'Happy' Now?" Unfortunately this won't help with >>> title("admiral von schneider") 'Admiral Von Schneider' # von should be lower case
- Previous message (by thread): str.title() fails with words containing apostrophes
- Next message (by thread): str.title() fails with words containing apostrophes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list