【问题标题】:Breaking long string without the spaces in Python在Python中打破没有空格的长字符串
【发布时间】:2013-10-12 02:29:35
【问题描述】:

所以,这是我的代码的 sn-p:

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

一行中的良好样式超过了 80 个字符,所以我这样做了:

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

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

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

谢谢!

【问题讨论】:

    标签: python string


    【解决方案1】:

    以下内容也适用于 Python 3+ 中较新的 string formatting technique

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

    【讨论】:

      【解决方案2】:

      不要在中间换行,而是使用由续行分隔的两个字符串,但最好是使用括号

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

      【讨论】:

        【解决方案3】:

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

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

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

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

        注意,字符串之间不需要+; Python 自动将连续的字符串文字合并为一个:

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

        我自己更喜欢括号。

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

        【讨论】:

        • 如果你有括号,你也可以在.字符之前或之后放置换行符。那是因为它是一种运算符(尽管我们通常不这么认为),并且运算符允许在它们的任一侧进行灵活的间距。
        • 我基本同意,但是当格式字符串只有一小部分自身包裹在第二行时(或者当缩进导致大部分问题,而不是长字符串时),它可以有用。我几乎总是在点之前打断,所以它是func("formatstring"<newline_and_indentation_upto_the_(>.format(args)),这似乎比其他选项好一点。
        • 有趣的是,至少在我的字体中,我的评论完全正确地缩进以显示我的意思......
        • @Blckknght:通常有更好的选择。比如先将较长的格式字符串定义为变量。
        猜你喜欢
        • 2013-06-10
        • 1970-01-01
        • 2020-08-02
        • 1970-01-01
        • 1970-01-01
        • 2016-06-29
        • 1970-01-01
        • 2013-09-19
        • 1970-01-01
        相关资源
        最近更新 更多