2011-03-25 54 views
116

为了服从python样式规则,我将编辑器设置为最多79列。Python风格 - 字符串延续?

在PEP中,它建议在括号,圆括号和大括号中使用python的隐含延续。但是,当我遇到字符串限制时处理字符串时,会变得有点奇怪。

例如,试图用一个多

mystr = """Why, hello there 
wonderful stackoverflow people!""" 

将返回

"Why, hello there\nwonderful stackoverflow people!" 

这工作:

mystr = "Why, hello there \ 
wonderful stackoverflow people!" 

因为它返回:

"Why, hello there wonderful stackoverflow people!" 

但是,当语句中缩进几个街区,这看起来奇怪:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there \ 
wonderful stackoverflow people!" 

如果你试图缩进第二行:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there \ 
      wonderful stackoverflow people!" 

你的字符串结束为:

"Why, hello there    wonderful stackoverflow people!" 

我发现解决这个问题的唯一方法是:

do stuff: 
    and more stuff: 
     and even some more stuff: 
      mystr = "Why, hello there" \ 
      "wonderful stackoverflow people!" 

我喜欢哪一种更好,但眼睛也有点不安,因为它看起来像是坐在无处不在的中间。这将产生正确的:

"Why, hello there wonderful stackoverflow people!" 

所以,我的问题是 - 什么是不显示我应该怎么做这个有些人对如何做到这一点,是有什么我失踪的风格指南中的建议?

谢谢。

+1

高缩进级别也可能是你需要重构代码,以便它更模块化 – Daenyth 2011-03-25 20:18:38

+5

我缩进那么多做出点的标志。但是要意识到,至少可以达到第三级缩进是很容易的,但是即使只有一个缩进级别,标准方法也会使字符串变得非常不合适。 – sjmh 2011-03-25 20:30:35

+0

可能重复的[在Python中换行长行](http://stackoverflow.com/questions/3346230/wrap-long-lines-in-python) – JrBenito 2016-09-27 19:18:06

回答

172

由于adjacent string literals are automatically joint into a single string,你可以用括号内的隐含续行所推荐的PEP 8:

print("Why, hello there wonderful " 
     "stackoverflow people!") 
+1

谢谢Sven,我比我使用的风格多一点。 – sjmh 2011-03-25 20:34:42

+1

我认为这只是一个窍门,但在阅读python文档后,我必须说,这很整齐。谢谢 ! – Medorator 2014-02-07 07:41:17

2

我解决此得到与

mystr = ' '.join(
     ["Why, hello there", 
     "wonderful stackoverflow people!"]) 
过去

。这并不完美,但对于需要在其中没有换行符的非常长的字符串来说,它非常适用。

+12

在我的机器上,这需要350纳秒,加入一个元组而不是列表需要250纳秒。另一方面,隐式加入只需要25ns。隐性加入在简单性和速度方面都是明显的赢家。 – endolith 2012-08-22 01:09:58

+6

@ endolith:我同意使用圆括号更好,因为它更干净,但这不是考虑性能的地方。如果您在运行时关心100 ns的差异,特别是在连接硬编码字符串时,会出现问题。 – nmichaels 2012-08-27 13:51:35

+0

如果不知道背景,我不会说关心100ns是错误的。如果发生了一百万次操作会怎么样? – Medorator 2014-02-07 07:42:45

18

只是指出,这是使用括号调用自动拼接。这很好,如果你碰巧已经在声明中使用它们。否则,我只会使用'\'而不是插入括号(这是大多数IDE为您自动执行的操作)。缩进应该对齐字符串延续,以便符合PEP8。例如:

my_string = "The quick brown dog " \ 
      "jumped over the lazy fox" 
2

另一种可能性是使用textwrap模块。这也避免了问题中提到的“串在一起”的问题。

import textwrap 
mystr = """\ 
     Why, hello there 
     wonderful stackoverfow people""" 
print (textwrap.fill(textwrap.dedent(mystr)))