如何在 Python 中使用分隔符字串分割字串?


字串是由字元組成的集合,可以表示單個單詞或完整的短語。與 Java 不同,不需要顯式宣告 Python 字串,可以直接將字串值賦值給字面量。

字串是 String 類的物件,其中包含多個內建函式和方法來操作和訪問字串。

在本文中,我們將瞭解如何在 Python 中使用分隔符字串分割字串。

使用 split() 方法

一種使用分隔符分割字串的方法是使用字串類內建方法 split()。此方法接受字串值作為引數,並將更新後的分隔符字串作為輸出返回。

它還有一個可選引數表示分隔符。如果未提及分隔符,則預設情況下空格被視為分隔符。還有一個名為 maxsplit 的可選引數,它告訴我們使用者希望進行多少次分割。

示例 1

在下面給出的示例中,我們獲取一個用 – 分隔的字串輸入,並使用 split() 方法進行分割。

str1 = "Welcome to Tutorialspoint" print("The given input string is") print(str1) print("The string after split ") print(str1.split())

輸出

上面給定程式的輸出為:

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to', 'Tutorialspoint']

示例 2

在下面,我們使用分隔符 # 分割字串。

str1 = "Hello#how#are#you" print("The given input string is") print(str1) print("The string after split ") print(str1.split("#"))

輸出

The given input string is
Hello#how#are#you The string after split ['Hello', 'how', 'are', 'you']

使用正則表示式

我們也可以使用正則表示式在 python 中分割字串。為此,需要使用 re 庫的 split() 函式。它有兩個引數,分隔符和輸入字串。它返回更新後的字串作為輸出。

示例 1

在下面給出的示例中,我們獲取一個用 – 分隔的字串輸入,並使用 split() 方法進行分割,並將 maxsplit 設定為 1。

str1 = "Welcome to Tutorialspoint" print("The given input string is") print(str1) print("The string after split ") print(str1.split(' ',1))

輸出

上面給定示例的輸出為:

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to Tutorialspoint']

示例 2

在下面給出的示例中,我們獲取一個字串作為輸入,並使用 re.split() 方法使用分隔符“ ”進行分割。

import re str1 = "Welcome to Tutorialspoint" print("The given input string is") print(str1) print("The string after split ") print(re.split(' ',str1))

輸出

上面給定程式的輸出為:

The given input string is
Welcome to Tutorialspoint
The string after splitted
['Welcome', 'to', 'Tutorialspoint']

示例 3

在下面給出的示例中,我們獲取一個字串作為輸入,並使用 re.split() 方法使用分隔符“ ”進行分割,並將 maxsplit 設定為 1。

import re str1 = "Welcome to Tutorialspoint" print("The given input string is") print(str1) print("The string after split ") print(re.split(' ',str1,1))

輸出

上面給定示例的輸出為:

The given input string is
Welcome to Tutorialspoint
The string after split
['Welcome', 'to Tutorialspoint']

更新於: 2022-10-19

2K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.