This may not be the most straight forward way, it's not efficient, but it outlines the process that lies within the pythonic one liners:
def example_text_wrap_function(takes_a_string,by_split_character,line_length_int):
str_list = takes_a_string.split(by_split_character)
tot_line_length = 0
line = ""
line_list = []
for word in str_list:
# line_length_int - 1 to account for \n
if len(line) < (line_length_int - 1):
# check if first word
if line is '':
line = ''.join([line,word])
# Check if last character is the split_character
elif line[:-1] is by_split_character:
line = ''.join([line,word])
# else join by_split_character
else:
line = by_split_character.join([line,word])
if len(line) >= (line_length_int - 1):
# last word put len(line) over line_length_int start new line
# split(by_split_character)
# append line from range 0 to 2nd to last "[0:-2]" and \n
# to line_list
list_out = by_split_character.join(line.split(by_split_character)[0:-1]), '\n'
str_out = by_split_character.join(list_out)
line_list.append(str_out)
# set line to last_word and continue
last_word = line.split(by_split_character)[-1]
line = last_word
# append the last line if word is last
if word in str_list[-1]:
line_list.append(line)
print(line_list)
for line in line_list:
print(len(line))
print(repr(line))
return ''.join(line_list)
# if the script is being run as the main script 'python file_with_this_code.py'
# the code below here will run. otherwise you could save this in a file_name.py
# and in a another script you could "import file_name" and as a module
# and do something like file_name.example_text_wrap_function(str,char,int)
if __name__ == '__main__':
tmp_str = "This is a string with length of some arbitrary number greater than 20"
results = example_text_wrap_function(tmp_str,' ',20)
print(results)