Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串拆分为正数和负数?_Python_String_Split - Fatal编程技术网

Python 将字符串拆分为正数和负数?

Python 将字符串拆分为正数和负数?,python,string,split,Python,String,Split,我希望能够拆分如下内容: "20 - 5 - 4 + 10 + 4" 将其中一个作为有符号的数字放入一个列表中: ["20", "-5", "-4", "+10", "+4"] 或分成两个列表作为未签名: ["20", "10", "4"] ["5", "4"] 在python中是否有一个内置方法可以用来执行此操作?您可以使用re.findall: import re s = "20 - 5 - 4 + 10 + 4" new_s = re.findall('[-+]?\d+', s.re

我希望能够拆分如下内容:

"20 - 5 - 4 + 10 + 4"
将其中一个作为有符号的数字放入一个列表中:

["20", "-5", "-4", "+10", "+4"]
或分成两个列表作为未签名:

["20", "10", "4"]
["5", "4"]

在python中是否有一个内置方法可以用来执行此操作?

您可以使用
re.findall

import re
s = "20 - 5 - 4 + 10 + 4"
new_s = re.findall('[-+]?\d+', s.replace(' ', ''))
输出:

['20', '-5', '-4', '+10', '+4']

没有
regex
,但如果没有空格或任何其他运算符,则会中断

expr = "20 - 5 - 4 + 10 + 4"
tokens = expr.split()
if tokens[0].isnumeric():tokens = ['+'] + tokens
tokens = [''.join(t) for t in zip(*[iter(tokens)]*2)]
pos = [t.strip('+') for t in tokens if '+' in t]
neg = [t.strip('-') for t in tokens if '-' in t]
或者按照
@Sayse
的建议:

tokens = expr.replace('- ','-').replace('+ ','+').split()
pos = [t.strip('+') for t in tokens if '-' not in t]
neg = [t.strip('-') for t in tokens if '-' in t]

可以简化为
re.findall('[-+]?\d++',s.replace('',)
。在这里总是使用原始字符串也是一个好习惯。