当前位置:   article > 正文

python的split()函数!_python中split()函数

python中split()函数

split是python内置的一个函数,主要是对字符串进行分割,分隔后的字符串以列表方式返回,是字符串处理方法的重要方法之一。格式:

string.split(separator, number)

其中sepatator为分隔符,常见的有“,”,“/”,“ ”......

number代表分割的次数,为可选参数。一般情况下,我们不使用该参数。

>>> string="math and code"

>>> string.split(" ")

['math', 'and', 'code']

>>> string="math,and,code"

>>> string.split(",")

['math', 'and', 'code']

>>> string="math/and/code"

>>> string.split("/")

['math', 'and', 'code']

上述皆没使用第二个参数

当然,下面使用第二个参数,看看会有什么效果!

>>> string="math and code"

>>> string.split(" ",1)

['math', 'and code']

>>> string.split(" ",2)

['math', 'and', 'code']

当然,有些时候不需要输入任何参数也可分割,默认以空格,tab空格符,回车符等作为分割条件。

>>> string="math and code"#空格

>>> string.split()

['math', 'and', 'code']

>>> string="math\tand\tcode"#tab键

>>> print(string)

math    andcode

>>> string.split()

['math', 'and', 'code']

>>> string="math\nand\ncode"#回车符

>>> print(string)

math

and

code

>>> string.split()

['math', 'and', 'code']

当然,值得注意的一点是字符串使用split方法时,结果会以一个列表的形式返回,原来的对象(字符串)并不会发生改变!这是值得特别关注的地方。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/煮酒与君饮/article/detail/785972
推荐阅读
相关标签
  

闽ICP备14008679号