What is the pythonic way to output numerous multiline strings that require formatting?

139 views Asked by At

My python application is a pre-processor; my outputs are the inputs of another application. The other application has various multi-line section headers that have subtle changes dependent on the version. My application fills the sections.

My current "printer" defines several multiline strings with format substitutions. The print statements will be replaced with write ones:

def generate():
    header="""
        Multi-line header
        Symbols that form a logo
        changes  with version
        """
    anotherSection="""
        this section header 
        is shorter
        (
            {myFiller}
        )
        """

    print header
    print anotherSection.format(myFiller = "{}{}{}".format(myFiller.content))
    print anotherSection2.format(myFiller = [x.strip() for x in myFiller.content2])
    print anotherSection3.format(myFiller = myFiller3.content)

"myFiller" is a call to a class with raw data that may need to be formatted based on the section.

Something doesn't feel right about having a bunch of multi-line strings clouding the actual "printing". The .format(.format) stuff may get a little difficult to read as well.

Any thoughts on how to structure this?

I've been toying with a dictionary of section strings but I didn't like the print statement interface (not that I'm sold on individual print statements:

format_requirements={'header': """.....""",'section':"""...."""}

print format_requirements['header'].format(....)

The version I"m leaning towards uses functions for each section string definition. This is nice for version changes but I'm not sure it's the way to go (I'm mainly concerned with convoluting my generate function with a bunch of other functions):

def header(version):
    header=""
    if version == v1:
        header="""...."""
    if version ==v2:
        header="""..."""
    return header
def section(type):
   section="""...."""
   return section

print header(v1).format(....)
print section

I've also played with classes, iterating over list, and a few other things. After reading the style guide (nudged me into the .format() direction) and various posts I've come here for direction on something more pythonic and legible to others.

I'm open to any guidance and ways to structure this.

Thanks!

1

There are 1 answers

3
skolsuper On

I would go with a class that keeps the raw input in ._data attributes and has methods to output the correctly formatted strings for each "version"

class MyStringFormatter(object):

    def __init__(header=None, content=None):
        self._data = {'header': header, 'content': content}

    def version_one(self):
        # format strings here
        return stringv1