Last active
November 16, 2016 01:17
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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