如何使用Python的split()函数以指定分隔符将字符串拆分为列表?
发布时间:2023-07-06 00:32:51
Python的split()函数可以用来将一个字符串以指定的分隔符拆分为一个列表。该函数的使用格式为:
string.split(separator, maxsplit)
其中,string是要拆分的字符串,separator是用来拆分字符串的分隔符,maxsplit是可选的参数,用来指定最大拆分次数,默认为-1,表示不限制拆分次数。
下面是一些使用split()函数的例子:
1. 拆分以空格为分隔符的字符串为列表:
sentence = "Hello world! This is a sentence."
words = sentence.split(" ")
print(words)
输出:
['Hello', 'world!', 'This', 'is', 'a', 'sentence.']
2. 拆分以逗号为分隔符的字符串为列表:
numbers = "1,2,3,4,5"
num_list = numbers.split(",")
print(num_list)
输出:
['1', '2', '3', '4', '5']
3. 拆分以换行符为分隔符的字符串为列表:
text = "Line 1
Line 2
Line 3"
lines = text.split("
")
print(lines)
输出:
['Line 1', 'Line 2', 'Line 3']
4. 拆分以连续的多个分隔符为分隔符的字符串为列表:
data = "apple,banana,,grape,orange"
fruits = data.split(",") # 使用逗号分隔符拆分
print(fruits)
输出:
['apple', 'banana', '', 'grape', 'orange']
5. 限制拆分次数:
text = "one,two,three,four,five"
items = text.split(",", 2) # 限制拆分次数为2次
print(items)
输出:
['one', 'two', 'three,four,five']
需要注意的是,split()函数返回的是一个拆分后的列表,原始字符串并不会被改变。
