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

时间:2022-05-17 02:23:17

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(self.theta)) 

It goes beyond the 80 chars for good styling in a line, so I did this:

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

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

I added the "\" to break up the string, but then there is this huge blank gap when I print it.

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

How would you split the code without distorting it?

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

Thanks!

2 个解决方案

#1


14  

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:

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

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

I prefer parenthesis myself.

我自己更喜欢括号。

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

str()调用是多余的;默认情况下,.format()会为您执行此操作。

#2


1  

Don't break the line in between instead use two strings separated by line continuation but best would be to use brackets

不要破坏它们之间的界限,而是使用由续行分隔的两个字符串,但最好是使用括号

return ("a Parallelogram with side lengths {} and {}, and interior angle "
"{}".format(1, 2, 3))

#1


14  

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:

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

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

I prefer parenthesis myself.

我自己更喜欢括号。

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

str()调用是多余的;默认情况下,.format()会为您执行此操作。

#2


1  

Don't break the line in between instead use two strings separated by line continuation but best would be to use brackets

不要破坏它们之间的界限,而是使用由续行分隔的两个字符串,但最好是使用括号

return ("a Parallelogram with side lengths {} and {}, and interior angle "
"{}".format(1, 2, 3))