你几乎拥有它。
import re
regex = re.compile(r'(\d+)|([\+-]?\d+)')
s = "1 2 3 4 5 6 +1 +2 +3 -1 -2 -3 +654 -789 321"
for r in regex.findall(s):
if r[0]:
# whole (unsigned)
print 'whole', r[0]
elif r[1]:
# a signed integer
print 'signed', r[1]
结果:
>>>
whole 1
whole 2
whole 3
whole 4
whole 5
whole 6
signed +1
signed +2
signed +3
signed -1
signed -2
signed -3
signed +654
signed -789
whole 321
或者,您可以使用“或”以“更好”的方式获得实际结果:
print [r[0] or r[1] for r in regex.findall(s)]
>>>
['1', '2', '3', '4', '5', '6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '321']
编辑:根据您的问题“是否可以将'10'存储为'+10' ”:
import re
def _sign(num):
if r[0]:
return '+%s'%r[0]
else:
return r[1]
regex = re.compile(r'(\d+)|([\+-]?\d+)')
s = "1 2 3 4 5 6 +1 +2 +3 -1 -2 -3 +654 -789 321"
print [_sign(r) for r in regex.findall(s)]
>>>
['+1', '+2', '+3', '+4', '+5', '+6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '+321']
或在 1 行中:
print ['+%s'%r[0] if r[0] else r[1] for r in regex.findall(s)]
>>>
['+1', '+2', '+3', '+4', '+5', '+6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '+321']