Skip to content

Instantly share code, notes, and snippets.

@rossgoodwin
Created March 26, 2016 20:38
Show Gist options
  • Save rossgoodwin/afacb992fdc13f11c26c to your computer and use it in GitHub Desktop.
Save rossgoodwin/afacb992fdc13f11c26c to your computer and use it in GitHub Desktop.
Function to format text for a variable maximum line length
import string
def split_to_lines(text, ll=80):
text_list = filter(
lambda x: x in string.printable,
list(text.strip())
)
char_count = 0
ws_indexes = list()
cur_line = list()
all_lines = list()
i = 0
start_ix = 0
while i < len(text_list):
c = text_list[i]
# print c
if c in [' ', '\t']:
ws_indexes.append(i)
cur_line.append(c)
char_count += 1
if c == '\n':
cur_line = text_list[start_ix:i]
start_ix = i
all_lines.append(''.join(cur_line))
cur_line = list()
char_count = 0
elif char_count >= ll:
tgt_ix = ws_indexes.pop()
cur_line = text_list[start_ix:tgt_ix]
i = tgt_ix
start_ix = i
all_lines.append(''.join(cur_line))
cur_line = list()
char_count = 0
i += 1
all_lines.append(''.join(cur_line))
return map(lambda x: x.strip(), all_lines)
@prasenjithalder
Copy link

hi use help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment