Breaking long string without the spaces in Python

后端 未结 2 1117
暖寄归人
暖寄归人 2020-12-11 02:38

So, here is a snippet of my code:

return \"a Parallelogram with side lengths {} and {}, and interior angle 
{}\".format(str(self.base), str(self.side), str(s         


        
2条回答
  •  一生所求
    2020-12-11 03:07

    You can put parenthesis around the whole expression:

    return ("a Parallelogram with side lengths {} and {}, and interior "
            "angle {}".format(self.base, self.side, self.theta))
    

    or you could still use \ to continue the expression, just use separate string literals:

    return "a Parallelogram with side lengths {} and {}, and interior " \
           "angle {}".format(self.base, self.side, self.theta)
    

    Note that there is no need to put + between the strings; Python automatically joins consecutive string literals into one:

    >>> "one string " "and another"
    'one string and another'
    

    I prefer parenthesis myself.

    The str() calls are redundant; .format() does that for you by default.

提交回复
热议问题