Last active
August 29, 2015 14:06
-
-
Save eaydin/f419171dbbbf07913ce9 to your computer and use it in GitHub Desktop.
Split long String into lists with limited length
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
| ### useful when parsing strings to paragraphs | |
| ### to reassemble from lists with each element | |
| ### having a maximum length | |
| ### useful for low level reportlab pdf creation | |
| ### usage: stripLongString("My Very Extra Long String", maximumLengthINTEGER) | |
| ### Returns an array | |
| def chunkstring(string, length): | |
| #got this from http://stackoverflow.com/a/18854817/1278994 | |
| return [string[0+i:length+i] for i in range(0, len(string), length)] | |
| def stripLongString(string, length): | |
| a = [] | |
| new=[] | |
| # this for loop checks if there are "words" exceeding the "length" limit | |
| # if there are, we will split them into chunks of max. "length" elements | |
| for word in string.split(): | |
| if len(word) > length: | |
| new = chunkstring(word, length) | |
| a = a + new | |
| else: | |
| a.append(word) | |
| out = [] | |
| bunk = [] | |
| # now let's iterate over each "word" (including the chunks from above) | |
| # and see if when combining them, we exceed the "length" limit | |
| # when we exceed, that's the point to stop adding them together | |
| for idx, i in enumerate(a): | |
| if bunk != []: | |
| if len(" ".join(bunk) + " " + i) > length: | |
| out.append(" ".join(bunk)) | |
| bunk = [] | |
| elif idx + 1 == len(a): | |
| bunk.append(i) | |
| out.append(" ".join(bunk)) | |
| else: | |
| bunk.append(i) | |
| if bunk == []: | |
| bunk.append(i) | |
| if idx+1 == len(a): | |
| out.append(i) | |
| return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment