2011-12-20 22 views
25

我有一个很长的字符串在Python:如何在Python中声明一个长字符串?

long_string = ' 
this is a really 
really 
really 
long 
string 
' 

然而,由于字符串跨越多行,蟒蛇不承认这是一个字符串。我该如何解决?

+1

把它放在'“”“...”“”'中。 '“”“long-long-string”“”' – khachik 2011-12-20 14:34:21

+0

是否为文档字符串保留三重引号? – ffledgling 2013-04-17 11:12:37

+2

@ffledgling它保留为多行字符串,用于文档字符串 – Winand 2016-03-02 05:16:49

回答

32
long_string = ''' 
this is a really 
really 
really 
long 
string 
''' 

"""做同样的事情。

+3

在缩进字符串的行使代码更具可读性的情况下,可以使用'dedent'来移除结果字符串中的缩进。 – IanS 2016-08-30 10:11:07

20

您可以使用

long_string = 'fooo' \ 
'this is really long' \ 
'string' 

,或者如果你需要换行

long_string_that_has_linebreaks = '''foo 
this is really long 
''' 
+4

另外,如果您的圆括号绕过了字符串,那么对于第一个选项,您不需要反斜杠。但是请注意使用字符串连接的最大缺点:除非你对空格非常小心,否则最终可能会出现''fooothis真的很长“,这可能不是你想要的。 – Duncan 2011-12-20 16:00:19

66

你也可以做到这一点,这是很好的,因为你有串内通过空格更好的控制:

long_string = (
    'Lorem ipsum dolor sit amet, consectetur adipisicing elit, ' 
    'sed do eiusmod tempor incididunt ut labore et dolore magna ' 
    'aliqua. Ut enim ad minim veniam, quis nostrud exercitation ' 
    'ullamco laboris nisi ut aliquip ex ea commodo consequat. ' 
    'Duis aute irure dolor in reprehenderit in voluptate velit ' 
    'esse cillum dolore eu fugiat nulla pariatur. Excepteur sint ' 
    'occaecat cupidatat non proident, sunt in culpa qui officia ' 
    'deserunt mollit anim id est laborum.' 
) 
+2

事实上,这是我想用一个元素创建一个元组时遇到的事情之一;) – plaes 2011-12-20 16:20:57

+0

当您需要任何不是字符串的评估值时,这似乎不起作用。通常对我来说,当使用列表理解来将复杂数据内插到一个字符串中时;并且我还没有找到一种方法将这种表达式与此字符串定义样式结合起来。 :( – ThorSummoner 2015-11-25 19:58:17

+0

你也可以使用long_string = textwrap.dedent('''长字符串,每行缩进''')https://docs.python.org/3/library/textwrap.html#textwrap.dedent – moorecm 2015-12-01 19:33:14

4

我也能够使它像这样工作。

long_string = '\ 
this is a really \ 
really \ 
really \ 
long \ 
string\ 
' 

我找不到构造多线串这样任何在线引用。我不知道这是否正确。我怀疑Python是因为反斜杠而忽略了换行符?也许有人可以阐明这一点。

+1

另外,崇高文本(Build 3114)似乎在语法高亮显示时遇到了麻烦。 – 2016-07-19 23:51:02

相关问题