如何在 Python 中按換行符分割字串?
在本文中,我們將瞭解如何在 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
在下面給出的示例中,我們使用與上面相同的程式,但我們使用不同的子字串進行檢查。 −
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']
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP