如何將多行字串拆分成多行?


字串是由字元組成的集合,可以用來表示單個單詞或整個短語。字串在Python中非常有用,因為它們不需要顯式宣告,並且可以使用或不使用說明符進行定義。為了處理和訪問字串,Python包含許多內建方法和函式。字串是String類的物件,由於Python中的一切都是物件,因此它包含多個方法。

在本文中,我們將瞭解如何在Python中將多行字串拆分成多行。

第一種方法是使用內建的splitlines()方法。它接受多行字串作為輸入,並輸出在每行換行符處分割的字串。不需要任何引數。splitlines() 方法是一個內建字串方法,僅用於分割換行符。

示例1

在下面給出的程式中,我們接受一個多行字串作為輸入,並使用splitlines() 方法在換行符處分割字串。

str1 = "Welcome\nto\nTutorialspoint"

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.splitlines())

輸出

以上示例的輸出如下:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

示例2

在下面給出的示例中,我們使用相同的splitlines() 方法在換行符處進行分割,但我們以不同的方式獲取輸入。

str1 = """Welcome
To
Tutorialspoint"""

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.splitlines())

輸出

以上示例的輸出如下:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

使用split()方法

第二種方法是使用內建方法split()。需要一個引數:應在該字元處分割提供的文字的字元。如果我們想在換行符處分割,則應使用引數'n'。與splitlines()函式不同,split()方法可以在任何字元處分割。我們只需要傳送字串應該在哪個字元處分割。

示例1

在下面給出的示例中,我們接受一個字串作為輸入,並使用split() 方法在換行符處分割字串。

str1 = "Welcome\nto\nTutorialspoint"

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.split('\n'))

輸出

以上示例的輸出如下所示:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

示例2

在下面給出的示例中,我們使用相同的split() 方法在換行符處進行分割,但我們以不同的方式獲取輸入。

str1 = """Welcome
To
Tutorialspoint"""

print("The given string is")
print(str1)

print("The resultant string split at newline is")
print(str1.split('\n'))

輸出

以上示例的輸出如下所示:

The given string is
Welcome
to
Tutorialspoint
The resultant string split at newline is
['Welcome', 'to', 'Tutorialspoint']

更新於:2022年12月7日

6K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告