Search code examples
pythonsyntax-errorconcatenationstring-interpolation

concatenation of triple quoted strings


I am currently trying to concatenate within a triple-quoted string using variables. What is the best way to go about this?

print('''
Points left to spend: ''' + str(pointsLeft) + '''
''' + str(attrChoice) + ':\t' + '''[''' + str(charAttr[attrChoice]) + ''']
To reduce the number of points spent on this skill, simply enter a negative number.
'''
)

The error message I got was: keyword can't be an expression. Could anyone explain what this means and if it is at all possible to attempt such a concatenation?


Solution

  • The best way to do that is with str.format:

    template = """This is a 
    multiline {0} with
    replacement {1} in."""
    
    print(template.format("string", "fields"))
    

    From Python 3.6 (see PEP 498) you can do this using an "f-string" as follows:

    print(f'''
    Points left to spend: {pointsLeft}
    {attrChoice}:\t[{charAttr[attrChoice]}]
    To reduce the number of points spent on this skill, simply enter a negative number.
    '''
    )