欢迎访问宙启技术站
智能推送

Python中的字符串切割方法:split函数的用法

发布时间:2023-06-26 13:39:24

Python是一门非常强大的编程语言,里面有许多函数可供使用。字符串是编程语言中经常使用的一种数据类型,而字符串的切割操作则是处理字符串的常见需求之一。在Python中,有一个内置的字符串切割函数——split函数,它能够根据指定的分隔符,将一个字符串分割成多个子字符串,并将这些子串存储到一个列表(List)中。本文将为您详细介绍Python中的split函数及其用法。

语法:

在Python中,split函数的基本语法如下:

str.split(str = "", num = string.count(str)). 

参数说明:

str:表示指定的分隔符,默认为空格(' ')。

num:表示分割的次数,如果指定,那么将分割成指定的次数,如果不指定,那么将全部分割。默认为 -1,即分割所有。

返回值说明:

返回分割后的字符串列表。

实例分析:

接下来,我们通过一些实例,来详细介绍split函数的用法。

实例1:

我们首先来看一个最基本的split函数的实例。

>>> str = "Python is a powerful and easy-to-learn programming language"

>>> list = str.split()

>>> print(list)

输出:

['Python', 'is', 'a', 'powerful', 'and', 'easy-to-learn', 'programming', 'language']

这段代码中,我们定义了一个字符串变量str,然后调用split()函数,将字符串分割成多个子字符串,并将这些子串存储到一个列表(List)中。因为默认的分隔符为' ',所以程序会根据空格来分割字符串。

实例2:

接下来,我们将尝试使用不同的分隔符来分割字符串。并将分割后得到的字符串存储到一个列表(List)中。

注意:在指定分隔符的时候,需要用引号将其括起来。

>>> str = "Be simple, easy and secure! Let's use Python"

>>> list = str.split(",") #用逗号来分割字符串

>>> print(list)

输出:

['Be simple', ' easy and secure! Let\'s use Python']

这段代码中,我们使用逗号作为分隔符,将字符串分割成两个子字符串,并将这些子串存储到一个列表(List)中。

实例3:

下面,我们使用num参数来指定分割字符串部分的数量。并将分割后得到的字符串存储到一个列表(List)中。

>>> str = "Python is a powerful and easy-to-learn programming language"

>>> list = str.split(' ', 3)

>>> print(list)

输出:

['Python', 'is', 'a', 'powerful and easy-to-learn programming language']

我们将分割图放到一个列表中,观察输出结果。可以看到,此时我们只将字符串分割了三次。

实例4:

下面,我们将尝试使用非默认的分隔符。并且由于该字符串中没有分隔符的存在,因此我们可以使用len()函数检查所得到的列表中的元素个数。

>>> str1 = "Welcome to Blog. Python is the best language"

>>> str2 = "Thisisonlyonebigwordandnoonecanreadit"

>>> list1 = str1.split('.')

>>> list2 = str2.split('o')

>>> print(list1)

>>> print(list2)

>>> print(len(list2))

输出:

['Welcome to Blog', ' Python is the best language']

['Thisis', 'nly', 'nebigw', 'rdandn', '', 'necanreadit']

6

通过分析返回的结果,我们发现列表中的长度与字符串中分隔符的数量并无关系,因为该函数只分割由指定字符串分割出的部分,而其余部分相对于其它函数而言不能算是分隔符。

实例5:

split()函数还可以用来将字符串中的特定字符删掉,并进行分割。

>>> str = "Python,is,the,best,languae."

>>> list = str.split(',')

>>> print(list)

输出:

['Python', 'is', 'the', 'best', 'languae.']

通过观察,我们发现,该字符串中的逗号被去掉了,并进行了分割。

总结:

split()函数是Python中比较常用的字符串函数之一。它可以用默认分隔符来分隔字符串,也可以使用指定分隔符来分隔。此外,该函数还支持选择分隔的次数、删除指定字符串等参数。对于Python开发者来说,掌握该函数的用法是非常必要和基础的。