2011-05-09 15 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 
相關問題