Skip to content

Instantly share code, notes, and snippets.

@daviseford
Last active November 16, 2016 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save daviseford/297d7119636bbe67ffebd0b92fe57815 to your computer and use it in GitHub Desktop.
Save daviseford/297d7119636bbe67ffebd0b92fe57815 to your computer and use it in GitHub Desktop.
Python: Capitalize First Letter of Each Word in a String (including after punctuation)
import re
import string
def lowercase_match_group(matchobj):
return matchobj.group().lower()
# Make titles human friendly
# http://daviseford.com/python-string-to-title-including-punctuation
def title_extended(title):
if title is not None:
# Take advantage of title(), we'll fix the apostrophe issue afterwards
title = title.title()
# Special handling for contractions
poss_regex = r"(?<=[a-z])[\']([A-Z])"
title = re.sub(poss_regex, lowercase_match_group, title)
return title
def title_one_liner(title):
return re.sub(r"(?<=[a-z])[\']([A-Z])", lambda x: x.group().lower(), title.title())
str = "my dog's bone/toy has 'fleas' -yikes!"
assert title_extended(str) == "My Dog's Bone/Toy Has 'Fleas' -Yikes!"
# Note the errors that would occur with native implementations
assert str.title() == "My Dog'S Bone/Toy Has 'Fleas' -Yikes!"
assert string.capwords(str) == "My Dog's Bone/toy Has 'fleas' -yikes!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment