在非数字上拆分字符串

myo*_*yol 1 python split python-3.x

我试图在任何不是数字的字符串上拆分字符串.

orig = '0 1,2.3-4:5;6d7'
results = orig.split(r'\D+')
Run Code Online (Sandbox Code Playgroud)

我希望得到一个整数列表 results

0,1,2,3,4,5,6,7

但相反,我得到一个列表,其中包含一个与原始字符串匹配的字符串元素.

Pat*_*ner 5

嗯......你正在使用str.split() - 这需要角色分割 - 而不是正则表达式.您的代码将拆分'\D+'文本中的任何字符串:

orig = 'Some\\D+text\\D+tosplit'
results = orig.split(r'\D+')  # ['Some', 'text', 'tosplit']
Run Code Online (Sandbox Code Playgroud)

您可以使用re.split()代替:

import re

orig = '0 1,2.3-4:5;6d7'
results = re.split(r'\D+',orig)
print(results)
Run Code Online (Sandbox Code Playgroud)

要得到

['0', '1', '2', '3', '4', '5', '6', '7']
Run Code Online (Sandbox Code Playgroud)

使用data = list(map(int,results))转换为int.