在Python中打破没有空格的长字符串 [英] Breaking long string without the spaces in Python

查看:37
本文介绍了在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆