2011-12-20 25 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

相關問題