Python中的split()函數(shù)用于將字符串分割成一個(gè)列表。默認(rèn)情況下,split()函數(shù)將字符串以空格為分隔符進(jìn)行分割??梢酝ㄟ^參數(shù)指定其他的分隔符。例如:
str = "Hello World"
result = str.split()
print(result)
輸出結(jié)果為:
['Hello', 'World']
還可以通過指定分隔符參數(shù),將字符串分割成多個(gè)元素的列表。例如:
str = "1,2,3,4,5"
result = str.split(',')
print(result)
輸出結(jié)果為:
['1', '2', '3', '4', '5']
split()函數(shù)還可以通過指定分割次數(shù)參數(shù),限制分割的次數(shù)。例如:
str = "Hello World, How are you doing today?"
result = str.split(' ', 2)
print(result)
輸出結(jié)果為:
['Hello', 'World,', 'How are you doing today?']
此外,如果split()函數(shù)的參數(shù)為空字符串,那么它會(huì)將字符串的每個(gè)字符分割成一個(gè)列表元素。例如:
str = "Hello"
result = str.split('')
print(result)
輸出結(jié)果為:
['H', 'e', 'l', 'l', 'o']