Python split()函数如何工作
def loadTest(filename):
f=open(filename,'r')
k=0
line=f.readline()
labels=[]
vectors=[]
while line and k<4:
k=k+1
l=line[:-1].split(r'","')
s=float(l[0][1:])
tweet=l[5][:-1]
print(l)
line=f.readline()
f.close()
return
split(r'","')
python split方法内部实际上有什么作用?
-
原始字符串与Python字符串
r'","'
的 [R 是 表明 它是一个 原始字符串 。
原始字符串与常规python字符串有何不同?
该 特殊字符失去 其 内部特殊的意义 一个 原始字符串
。例如,\n
python字符串中的换行符将在原始字符串中失去其含义,仅表示反斜杠后跟n。string.split()
string.split()
将中断和拆分string
传递的参数,并返回列表中的所有部分。该列表将不包含分割字符。string.split('","')
将在每个字符串上进行分割和拆分,","
并返回列表中所有不完整的部分,但不包括","
例如:
print 'Hello world","there you are'.split(r'","')
输出:
['Hello world', 'there you are']
split()
可以做更多…您可以通过传入一个额外的参数来指定希望字符串分成多少部分。
让我们考虑以下字符串:
'hello,world,there,you,are'
-
对所有逗号进行拆分,并分成n + 1个部分,其中n是逗号数:
print ‘hello,world,there,you,are’.split(‘,’)
[‘hello’, ‘world’, ‘there’, ‘you’, ‘are’] -
在第一个逗号处分割,并且仅分成两部分。
‘hello,world,there,you,are’.split(‘,’,1)
[‘hello’, ‘world,there,you,are’] -
在第一个和第二个逗号处拆分,分为三个部分。等等…
‘hello,world,there,you,are’.split(‘,’,2)
[‘hello’, ‘world’, ‘there,you,are’]
甚至更多…
从文档:
如果未指定拆分字符(即,分隔符)或将其指定为None,则将应用不同的拆分算法:连续空格的运行将被视为单个分隔符,并且如果字符串中包含空格,则结果将不包含空字符串前导或尾随空格。因此,使用空分隔符分割空字符串或仅包含空格的字符串将返回[]。
例如,
>>>' 1 2 3 '.split() ['1', '2', '3'] >>>' 1 2 3 '.split(None, 1) ['1', '2 3 '] >>>''.split() [] >>>' '.split() [] >>>' '.split(None) []
乃至…
。
。
。
什么?
您是否正在寻找更多?别那么贪心:P。只是问问自己
?
,这会使您变得不贪心:D(如果您知道正则表达式,就会开玩笑) -