Python - re.split: extra empty strings that the beginning and end list
我正在尝试采用一串int和/或float并创建一个float列表。 该字符串将在其中包含这些需要忽略的括号。 我正在使用re.split,但是如果我的字符串以方括号开头和结尾,则会得到多余的空字符串。 这是为什么?
码:
1 2 3 4 5 6 | import re x ="[1 2 3 4][2 3 4 5]" y = "1 2 3 4][2 3 4 5" p = re.compile(r'[^\\d\\.]+') print p.split(x) print p.split(y) |
输出:
1 2 | ['', '1', '2', '3', '4', '2', '3', '4', '5', ''] ['1', '2', '3', '4', '2', '3', '4', '5'] |
如果使用
如果不希望这样,请将
例:
1 2 3 4 5 | import re a = '[1 2 3 4]' print(re.split(r'[^\\d]+', a)) print(re.findall(r'[\\d]+', a)) |
输出:
1 2 | ['', '1', '2', '3', '4', ''] ['1', '2', '3', '4'] |
正如其他人在他们的答案中指出的那样,这可能不是解决此问题的完美方法,但这是对问题标题中描述的问题的一般回答,当我使用Google找到该问题时,我也必须解决该问题。 。
您可以使用
1 2 3 4 | x ="[1 2 3 4][2 3 4 5]" print filter(None, re.split(r'[^\\d.]+', x)) //=> ['1', '2', '3', '4', '2', '3', '4', '5'] |
作为一种更Python的方式,您可以只使用列表推导和
1 2 | >>> [i for i in y if i.isdigit()] ['1', '2', '3', '4', '2', '3', '4', '5'] |
首先,关于代码,您需要根据空间或方括号(
1 2 3 4 5 6 7 8 | >>> y = "1 2 3 4][2 3 4 5" >>> re.split(r'[\\[\\] ]+',y) ['1', '2', '3', '4', '2', '3', '4', '5'] >>> y = "[1 2 3 4][2 3 4 5]" >>> re.split(r'[\\[\\] ]+',y) ['', '1', '2', '3', '4', '2', '3', '4', '5', ''] >>> re.split(r'[\\[\\] ]+',y.strip('[]')) ['1', '2', '3', '4', '2', '3', '4', '5'] |
您还可以使用
1 2 | >>> filter(bool,re.split(r'[\\[\\] ]+',y)) ['1', '2', '3', '4', '2', '3', '4', '5'] |
您可以使用正则表达式来捕获所需的内容,而不用分割字符串。您可以使用此正则表达式:
1 | (\\d+) |
工作演示
Python代码:
1 2 3 4 5 | import re p = re.compile(ur'(\\d+)') test_str = u"[1 2 3 4][2 3 4 5]" re.findall(p, test_str) |
1 2 3 4 5 | import re str="[1 2 3 4][2 3 4 5]" print re.findall(r'\\d+', str) str="1 2 3 4][2 3 4 5" print re.findall(r'\\d+', str) |