Python 的 split 函数如何将字符串分割成列表?
发布时间:2023-05-26 15:13:16
Python 的 split 函数是一个字符串方法,用于将字符串按照指定的分隔符进行分割,将分割后的结果存储在一个列表中返回。
基本语法:
string.split(separator, maxsplit)
其中,separator 是用于分割字符串的分隔符,maxsplit 是最多进行分割的次数,默认值为 -1。
例如:
sentence = "Hello World! Welcome to Python programming" words = sentence.split() print(words)
这段代码中,我们将字符串 sentence 按照空格分隔成了一个列表 words,输出结果为:
['Hello', 'World!', 'Welcome', 'to', 'Python', 'programming']
除了使用空格作为分隔符外,还可以使用其他的字符或字符串作为分隔符。例如,用逗号分隔一个字符串:
sentence = "apple, banana, orange, pineapple"
fruits = sentence.split(", ")
print(fruits)
这里使用了逗号和空格作为分隔符,输出结果为:
['apple', 'banana', 'orange', 'pineapple']
在这个例子中,我们使用了字符串 ", " 作为分隔符,即逗号后面跟一个空格。
另外,split 函数也支持通过 maxsplit 参数限制分割的次数。例如:
sentence = "apple, banana, orange, pineapple"
fruits = sentence.split(", ", 2)
print(fruits)
这里指定最多只分割 2 次,输出结果为:
['apple', 'banana', 'orange, pineapple']
可以看到,字符串 "orange, pineapple" 并没有被分割开,因为只允许最多分割 2 次。
需要注意的是,如果分隔符不在字符串中,split 函数将返回只包含整个字符串的列表。例如:
sentence = "Hello World!"
words = sentence.split(", ")
print(words)
这里的分隔符是 ", ",但是字符串中并不存在这个分隔符,所以结果会是:
['Hello World!']
除了 split 函数,Python 还提供了其他字符串方法,如 join、startswith、endswith 等,可以帮助我们更方便地处理字符串。掌握这些常用的字符串方法,可以有效提高编程的效率。
