在没有Python空格的情况下打破长字符串

mur*_*ros 7 python string

所以,这是我的代码片段:

return "a Parallelogram with side lengths {} and {}, and interior angle 
{}".format(str(self.base), str(self.side), str(self.theta)) 
Run Code Online (Sandbox Code Playgroud)

它超越了80个字符,在一条线上有良好的造型,所以我这样做:

return "a Parallelogram with side lengths {} and {}, and interior angle\
{}".format(str(self.base), str(self.side), str(self.theta)) 
Run Code Online (Sandbox Code Playgroud)

我添加了"\"来分解字符串,但是当我打印它时会出现这个巨大的空白间隙.

如何在不扭曲代码的情况下拆分代码?

谢谢!

Mar*_*ers 17

你可以在整个表达式周围加上括号:

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

或者您仍然可以使用\继续表达式,只需使用单独的字符串文字:

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

注意,没有必要放在+字符串之间; Python自动将连续的字符串文字连接成一个:

>>> "one string " "and another"
'one string and another'
Run Code Online (Sandbox Code Playgroud)

我自己更喜欢括号.

str()电话是多余的; .format()默认为你做这件事.