共計(jì) 754 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
在 Python 中,split() 函數(shù)用于字符串的分割。它基于指定的分隔符將字符串分割為多個(gè)子字符串,并返回一個(gè)包含這些子字符串的列表。以下是使用 split() 函數(shù)的基本語(yǔ)法:
string.split(separator, maxsplit)
其中,參數(shù) separator 是分隔符,可以是一個(gè)字符串或字符,默認(rèn)為 None,表示空格。maxsplit 是可選參數(shù),用于指定最大分割次數(shù)。
下面是一些示例:
# 使用空格分割字符串
string = "Hello World"
result = string.split()
print(result) # 輸出: ['Hello', 'World']
# 使用逗號(hào)分割字符串
string = "apple,banana,orange"
result = string.split(",")
print(result) # 輸出: ['apple', 'banana', 'orange']
# 使用換行符分割字符串
string = "apple\nbanana\norange"
result = string.split("\n")
print(result) # 輸出: ['apple', 'banana', 'orange']
# 指定最大分割次數(shù)
string = "apple,banana,orange"
result = string.split(",", 1)
print(result) # 輸出: ['apple', 'banana,orange']
注意,split() 函數(shù)返回的是一個(gè)列表,可以通過(guò)索引訪問(wèn)每個(gè)子字符串。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完