Last active
August 17, 2023 16:11
-
-
Save GLMeece/399ff616be5e61bf9d7254de29bf3b37 to your computer and use it in GitHub Desktop.
This file contains 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
"""Nice Title Case Function plus quick demo""" | |
def nice_title_case(str_in: str) -> str: | |
"""Converts a string to Title Case, with conventional exceptions which | |
need not be capitalized if they are not the first word in the title. | |
Reference: https://en.wikipedia.org/wiki/Title_case | |
*Note*: Prepositional rules are not strictly enforced | |
""" | |
exceptions_to_title_casing = ( | |
"a", "an", "and", "as", "at", | |
"but", "by", "for", "in", | |
"nor", "of", "on", "or", | |
"so", "the", "to", "up", "yet" | |
) | |
str_inter = str_in.title() | |
title_word_list = str_inter.split() | |
new_title_list = [] | |
title_length = len(title_word_list) | |
if title_length > 1: | |
new_title_list.append(title_word_list[0]) | |
for elem_cntr in range(1, title_length): | |
if title_word_list[elem_cntr].lower() in exceptions_to_title_casing: | |
new_title_list.append(title_word_list[elem_cntr].lower()) | |
else: | |
new_title_list.append(title_word_list[elem_cntr]) | |
final_output = ' '.join(new_title_list) | |
else: | |
final_output = str_inter | |
return final_output | |
if __name__ == "__main__": | |
# Just a quick test of the `nice_title_case` function | |
MY_OLD_TITLE = "the first title is but a temporary title of a better or worse title" | |
MY_NEW_TITLE = nice_title_case(MY_OLD_TITLE) | |
print(f"\nOrig. title: '{MY_OLD_TITLE}'") | |
print(f" New title: '{MY_NEW_TITLE}'\n") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment