Python字符串–split方法
描述: 这是字符串的分隔方法,主要有两个参数。第一个参数是“指定分隔符对字符串进行分隔”,第二个参数是“指定分隔的段数”,在这里需要注意的是:分隔的段数是设置的参数+1.
示例一,分隔符默认为所有的空字符,包括空格符,换行符,制表符等
str1="i need to leave,i'd like to do some anything important"
print(str1.split())
str1="i\nneed\nto\nleave,i'd\nlike\nto\ndo\nsome\nanything\nimportant"
print(str1.split())
str1="i\tneed\tto\tleave,i'd\tlike\tto\tdo\tsome\tanything\timportant"
print(str1.split())
print(type(str1.split()))
运行结果如下:
['i', 'need', 'to', "leave,i'd", 'like', 'to', 'do', 'some', 'anything', 'important']
['i', 'need', 'to', "leave,i'd", 'like', 'to', 'do', 'some', 'anything', 'important']
['i', 'need', 'to', "leave,i'd", 'like', 'to', 'do', 'some', 'anything', 'important']
<class 'list'>
在这里需要注意的是返回值是一个字符串列表!
示例二,指定分隔符
str1="i need to leave,i'd like to do some anything important"
print(str1.split("i",1))
print(str1.split("need",1))
print(str1.split("i need to leave"))
str2="i i i i i i"
print(str2.split("i"))
运行结果如下:
['', " need to leave,i'd like to do some anything important"]
['i ', " to leave,i'd like to do some anything important"]
['', ",i'd like to do some anything important"]
['', ' ', ' ', ' ', ' ', ' ', '']
1.在这里需要注意的是,第二个参数可以不设,如果不设置参数的话,就如第四个例子一样,有多少个字符就分+1段。 2.第一个参数可以是一个句子或者一段话。
文 | 戴眼镜的it小孩纸
|