Last active
March 26, 2020 13:42
-
-
Save lancejohnson/0608a900c9e7489fc3fc4be4352336bc to your computer and use it in GitHub Desktop.
A simple python function to split a string into a list of strings based on a character limit. It preserves the words entire. For instance if you have a limit of four characters "A dog" would be generated as ["A", "dog"] so as not to split up the word into ["A do", "g"]
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
def add_string_breaks(string): | |
list_words_in_str = string.split() | |
str_standard_whitespace = " ".join(list_words_in_str) | |
count_words_in_str = len(list_words_in_str) | |
slogan_lines = [] | |
i = 0 | |
possible_words_in_line = count_words_in_str | |
while i < possible_words_in_line: | |
text_already_newline = " ".join(slogan_lines) | |
print("Text already newline", text_already_newline) | |
text_to_newline = str_standard_whitespace.replace(text_already_newline, "") | |
list_words_to_newline = text_to_newline.split() | |
previous_word = i | |
current_word = i + 1 | |
current_str = " ".join(list_words_to_newline[:current_word]) | |
print(current_str) | |
word_char_count = len(" ".join(list_words_to_newline[:i+1])) | |
print(word_char_count) | |
if word_char_count < 15 and current_word < len(list_words_to_newline) + 1: | |
i += 1 | |
continue | |
else: | |
line_str = " ".join(list_words_to_newline[:previous_word]) | |
if len(line_str) > 15: | |
raise ValueError("First word of line too long") | |
else: | |
slogan_lines.append(line_str) | |
possible_words_in_line = count_words_in_str - current_word | |
words_in_slogan_lines = len(" ".join(slogan_lines).split()) | |
if words_in_slogan_lines < count_words_in_str: | |
i = 0 | |
else: | |
i = count_words_in_str | |
return slogan_lines |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment