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


字串是由一系列字元組成的集合,可以用來表示單個單詞或整個短語。字串在 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-07

6K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.