在Python中打破没有空格的长字符串 [英] Breaking long string without the spaces in Python
问题描述
所以,这是我的代码片段:
return "一个边长为 {} 和 {} 以及内角的平行四边形{}".format(str(self.base), str(self.side), str(self.theta))
它超出了一行 80 个字符的良好样式,所以我这样做了:
return "一个边长为 {} 和 {} 以及内角的平行四边形\{}".format(str(self.base), str(self.side), str(self.theta))
我添加了\"来拆分字符串,但是当我打印它时会出现这个巨大的空白.
如何在不扭曲代码的情况下拆分代码?
谢谢!
你可以在整个表达式周围加上括号:
return ("边长为 {} 和 {} 的平行四边形,以及内部"角度{}".格式(self.base,self.side,self.theta))
或者您仍然可以使用 \
来继续表达式,只需使用单独的字符串文字:
返回边长为 {} 和 {} 的平行四边形,以及内部的平行四边形" \角度{}".格式(self.base,self.side,self.theta)
注意字符串之间不需要放+
;Python 自动将连续的字符串字面量合二为一:
我自己更喜欢括号.
str()
调用是多余的;.format()
默认情况下会为您执行此操作.
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:
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!
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.
这篇关于在Python中打破没有空格的长字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!