0

supposing to have a long string to create and this string is within a method of a class, what is the best way to write the code?

def printString():

    mystring = '''title\n
    {{\\usepackage}}\n
    text continues {param}
    '''.format(param='myParameter')

    return mystring

this method is well formatted but the final string has unwanted spaces:

a = printString()
print(a)
title

    {\usepackage}

    text continues myParameter

while this method gives the corrected results but the code can become messy if the string(s) is long:

def printString():

    mystring = '''title\n
{{\\usepackage}}\n
text continues {param}
    '''.format(param='myParameter')

    return mystring

a = printString()
print(a)

title

{\usepackage}

text continues myParameter

some hints to have a good code quality and the results?

3 Answers 3

1

Try enclosing the string you want with brackets, like so:

def printString():

    mystring = ('title\n'
                '{{\\usepackage}}\n'
                'text continues {param}').format(param='myParameter')

    return mystring

This would allow you to break the string to several lines while c=having control over the whitespace.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use brackets to maintain tidiness of long strings inside functions.

def printString():
    mystring = ("title\n"
    "{{\\usepackage}}\n"
    "text continues {param}"
    ).format(param='myParameter')

    return (mystring)

print(printString())

Results in:

title
{\usepackage}
text continues myParameter

You may also wish to explicitly use the + symbol to represent string concatenation, but that changes this from a compile time operation to a runtime operation. Source

def printString():
    mystring = ("title\n" +
    "{{\\usepackage}}\n" +
    "text continues {param}"
    ).format(param='myParameter')

    return (mystring)

Comments

1

You can use re.sub to cleanup any spaces and tabs at the beginning of each lines

>>> import re
>>> def printString():
...     mystring = '''title\n
...     {{\\usepackage}}\n
...     text continues {param}
...     '''.format(param='myParameter')
...
...     return re.sub(r'\n[ \t]+', '\n', mystring)
... 

This gives the following o/p

>>> a = printString()
>>> print (a)
title

{\usepackage}

text continues myParameter

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.