0

I would like to cut coherently chars which are longer than 88 chars. I need this for line breaking in a reportlab table cell therefore I need additional whitespaces. The problem is the input can be anything and it would be great if the line breaking is useful.

My code is:

CONST = 88
def main():
    text = '''This is just a test to test the splitting of longer a path C\:TestResults\TestCase12345\SuiteOfTestCase2\LoggingAnything\LoggingTheLogger\PDFLoggerFiles\Example.pdf'''
    if len(text) > CONST:
        splitList = text.split(' ')
        for item in splitList:
            if len(item)>CONST:
                print searchChar(item)

def searchChar(toSplitString):
    chars = ['\\', '_']#...and catch other chars
    for char in chars:
        if toSplitString.find(char) != -1:
            splittedParts = toSplitString.split(char)
            for slicedParts in splittedParts:
                if len(splittedParts)>CONST:
                    break
        return buildNewString(splittedParts, char)
    print 'hard line breaking'

def buildNewString(stringParts, character):
    dummy = 0
    partOfTheNewString =''
    newStringList = []
    while dummy != len(stringParts):
        partOfTheNewString += (stringParts[dummy] + character)
        dummy = dummy +1
        if len(partOfTheNewString) > CONST:
            dummy = dummy -1
            sliceIndex = len(partOfTheNewString)-(len(stringParts[dummy])+len(character))
            partOfTheNewString = partOfTheNewString[:sliceIndex]
            partOfTheNewString += (' ')
            newStringList.append(partOfTheNewString)
            partOfTheNewString = ''
    if len(partOfTheNewString):
        index = len(partOfTheNewString) - len(character)
        newStringList.append(partOfTheNewString[:index])
    back = ''.join(newStringList)
    return back

if __name__ == '__main__':
    main()

This is too long and too branched. Do you have an idea?

That1Guy
  • 7,075
  • 4
  • 47
  • 59
Michael
  • 57
  • 1
  • 7
  • 1
    Take a look at the [textwrap](https://docs.python.org/2/library/textwrap.html) module. – Kevin Sep 11 '15 at 16:33

1 Answers1

0

Python will automatically concatenate strings that are just "next to" each other (see the docs, and note raw strings to preserve backslashes*):

text = (r'This is just a test to test the splitting '
        r'of longer a path C\:TestResults\TestCase12345'
        r'\SuiteOfTestCase2\LoggingAnything\LoggingTheLogger'
        r'\PDFLoggerFiles\Example.pdf')

Alternatively, if you're actually using multiline strings, see Avoiding Python multiline string indentation.

* but they still can't have a single backslash as the last character, see Why can't Python's raw string literals end with a single backslash?

Community
  • 1
  • 1
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437