Skip to content

Instantly share code, notes, and snippets.

@joedf
Last active February 18, 2020 22:28
Show Gist options
  • Save joedf/e94fe2a9ef949a289737dd5a4bca4e3a to your computer and use it in GitHub Desktop.
Save joedf/e94fe2a9ef949a289737dd5a4bca4e3a to your computer and use it in GitHub Desktop.
Returns title case avoiding title() 's double captilization of words with hyphens and apotrophes
def specialTitleCase(words):
# written by joedf (Feb. 2020), loosely inspired from https://github.com/gouch/to-title-case
# 1. assumes a list of short words to change to lower case
# 2. assumes short words are preceded by ' ' (or brackets), so that any "starting" ones are still capitalized.
# handle words within brackets
sWords = re.sub(r'[\(\[]',(lambda x:x.group(0)+' '),words)
# Avoid issue of title() capitalizing "2-part" tokens joined by a hyphen on an apostrophe.
# Also allows for "intentional" captilizations
sWords = ' '.join([word if bool(re.search(r'[A-Z]',word)) else word.capitalize() for word in sWords.split(' ')])
# titlecase with short words lowercased.
sWords = re.sub(r' (a|an|and|as|at|but|by|en|for|from|if|in|nor|of|on|or|per|the|to|v.?|vs.?|via|with)\b',( lambda x:x.group(0).lower() ),sWords,flags=re.IGNORECASE)
# realign brackets
return re.sub(r'[\(\[] ',(lambda x:x.group(0).rstrip()),sWords)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment