Python中split通过多个字符分割字符串

Python中的spilt方法只能通过指定的某个字符分割字符串,如s.split(’ ')
如果需要指定多个字符,需要用到re模块里的split方法。

cat test_split.py

import re

def split_str(s):
	fenge = [' ', '!', '.', ',', ':', '?', '......']
    pattern = ' '
    for char in fenge:
		if char != ' ':
			pattern += '|\\' + char
	s_list = re.split(pattern, s)
	#s_list = re.split(' |\!|\?|\.|\,', s)
	print s_list

if __name__ == '__main__':
	s = 'hello world!my name is tt,how are you?thank.you'
	split_str(s)

python test_split.py

['hello', 'world', 'my', 'name', 'is', 'tt', 'how', 'are', 'you', 'thank', 'you']

你可能感兴趣的:(python)