python字符串分割

        常用strip()去除字符串string首尾空格,在用split(‘XX’)将字符串string分成字符串列表。

e.g:

>>> s1 = '   123||456ab||789||  kd290b  ' * 2
>>> print s1
   123||456ab||789||  kd290b     123||456ab||789||  kd290b  
>>> def separate_string(string,spl = '||'):
	string = string.strip()
	slst = string.split(spl)
	for s in slst:
		s = s.strip()
		if s.isalnum():
			print s
		else:
			print 'String illegal!'

			
>>> separate_string(s1)
123
456ab
789
String illegal!
456ab
789
kd290b
>>> stemp = s1.strip()
>>> print stemp
123||456ab||789||  kd290b     123||456ab||789||  kd290b
>>> stemplist = stemp.split('||')
>>> print stemplist
['123', '456ab', '789', '  kd290b     123', '456ab', '789', '  kd290b']
>>> 
>>> s2 = '    1sd*q564 *2349d*   jh588  *   we890 *3dfghl  '
>>> separate_string(s2,'*')
1sd
q564
2349d
jh588
we890
3dfghl

        不用split()函数,用c++习惯去除空格分割字符串:

>>> s3 = '  uidd    3fg 23fd    rflkd  6ykpld     9dfghkotr    '
>>> def strip_space(string):
	string = string.strip()
	pos_start = string.find(" ")
	print string[:pos_start]  #the first ftring
	pos_end = pos_start
	while pos_end <= len(string) and pos_end != -1:
		while " " == string[pos_start]:
			pos_start = pos_start + 1
		pos_end = string.find(" ",pos_start)
		if -1 != pos_end:
			print string[pos_start:pos_end]
		else:
			print string[pos_start:]
		pos_start = pos_end

		
>>> strip_space(s3)
uidd
3fg
23fd
rflkd
6ykpld
9dfghkotr
>>> 


你可能感兴趣的:(Python)