如何在 Python 中根據空格分割字串?
在本文中,我們將瞭解如何在 Python 中根據空格分割字串。
第一種方法是使用內建方法split()。此方法根據我們所需的定界符分割給定的字串。split() 方法接受一個名為定界符的引數,它指定在哪個字元處分割字串。
因此,我們必須將空格作為定界符傳送到split() 方法。此方法返回修改後的列表,該列表在空格處分割。
示例
在下面給出的示例中,我們以字串作為輸入,並使用split() 方法在空格處分割字串−
str1 = "Hello Everyone Welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("The strings after the split are")
res = str1.split()
print(res)
輸出
上面示例的輸出如下所示−
The given string is Hello Everyone Welcome to Tutorialspoint The strings after the split are ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
使用 re.split() 函式
正則表示式用於第二種技術。匯入 re 庫,如果它尚未安裝,則安裝它以使用它。匯入 re 庫後,我們可以在 re.split() 函式中使用正則表示式“\s+”。re.split() 函式以正則表示式和字串作為引數,並在正則表示式指定的字元處分割字串。
示例
在下面給出的示例中,我們以字串作為輸入,並使用正則表示式在空格處分割字串−
import re
str1 = "Hello Everyone Welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("The strings after the split are")
res = re.split('\s+', str1)
print(res)
輸出
上面示例的輸出如下所示−
The given string is Hello Everyone Welcome to Tutorialspoint The strings after the split are ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
使用 re.findall() 函式
第三種方法是使用正則表示式的re.findall() 方法。此方法查詢所有不是空格的字串,因此從技術上講,它在空格處分割字串。
示例
在下面給出的示例中,我們以字串作為輸入,並使用re.findall() 方法在空格處分割字串−
import re
str1 = "Hello Everyone Welcome to Tutorialspoint"
print("The given string is")
print(str1)
print("The strings after the split are")
res = re.findall(r'\S+', str1)
print(res)
輸出
上面示例的輸出如下所示−
The given string is Hello Everyone Welcome to Tutorialspoint The strings after the split are ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP