Skip to main content
 首页 » 编程设计

Python:将字符串拆分为单词,保存分隔符

2025年05月04日15hnrainll

我有一个字符串:

'Specified, if char, else 10 (default).' 

我想把它分成两个元组

words=('Specified', 'if', 'char', 'else', '10', 'default') 
 
separators=(',', ' ', ',', ' ', ' (', ').') 

有没有人能快速解决这个问题?

PS:这个符号'-'是单词分隔符,不是单词的一部分

请您参考如下方法:

import re 
line = 'Specified, if char, else 10 (default).' 
words = re.split(r'\)?[, .]\(?', line) 
# words = ['Specified', '', 'if', 'char', '', 'else', '10', 'default', ''] 
separators = re.findall(r'\)?[, .]\(?', line) 
# separators = [',', ' ', ' ', ',', ' ', ' ', ' (', ').'] 

如果你真的想要元组传递 tuple() 中的结果,如果您不希望 words 有空条目(在逗号和空格之间),请使用以下内容:

words = [x for x in re.split(r'\)?[, .]\(?', line) if x] 

或

words = tuple(x for x in re.split(r'\)?[, .]\(?', line) if x)