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方法时,结果会以一个列表的形式返回,原来的对象(字符串)并不会发生改变!这是值得特别关注的地方。

你可能感兴趣的:(有趣的python,linq,p2p,wpf)