2011-05-09 44 views

回答

11

试试这个:

s = "this is a\nsentence" 
re.split(r'(\W+)', s) # Notice parentheses and a plus sign. 

结果将是:

['this', ' ', 'is', ' ', 'a', '\n', 'sentence'] 
+1

感谢。我应该更仔细地阅读're.split'文档。 – 2011-05-09 03:11:43

3

试试这个:在重新空白

re.split('(\W+)','this is a\nsentence') 
4

符号是'\ S'没有“ \ W'

比较:

import re 


s = "With a sign # written @ the beginning , that's a\nsentence,"\ 
    '\nno more an instruction!,\tyou know ?? "Cases" & and surprises:'\ 
    "that will 'lways unknown **before**, in 81% of time$" 


a = re.split('(\W+)', s) 
print a 
print len(a) 
print 

b = re.split('(\s+)', s) 
print b 
print len(b) 

产生

['With', ' ', 'a', ' ', 'sign', ' # ', 'written', ' @ ', 'the', ' ', 'beginning', ' , ', 'that', "'", 's', ' ', 'a', '\n', 'sentence', ',\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction', '!,\t', 'you', ' ', 'know', ' ?? "', 'Cases', '" & ', 'and', ' ', 'surprises', ':', 'that', ' ', 'will', " '", 'lways', ' ', 'unknown', ' **', 'before', '**, ', 'in', ' ', '81', '% ', 'of', ' ', 'time', '$', ''] 
57 

['With', ' ', 'a', ' ', 'sign', ' ', '#', ' ', 'written', ' ', '@', ' ', 'the', ' ', 'beginning', ' ', ',', ' ', "that's", ' ', 'a', '\n', 'sentence,', '\n', 'no', ' ', 'more', ' ', 'an', ' ', 'instruction!,', '\t', 'you', ' ', 'know', ' ', '??', ' ', '"Cases"', ' ', '&', ' ', 'and', ' ', 'surprises:that', ' ', 'will', ' ', "'lways", ' ', 'unknown', ' ', '**before**,', ' ', 'in', ' ', '81%', ' ', 'of', ' ', 'time$'] 
61 
相关问题