使用内置itertools模块中的pairwise()和chain():
# itertools.pairwise is available on python 3.10+, use this function on earlier versions
# copied from https://docs.python.org/3/library/itertools.html#itertools.pairwise
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
def split(s: str) -> typing.List[str]:
# iterate pairwise: "2+3" --> [("2", "+"), ("+", "3"), ("3", None)]
# the None is just added to get the last number right
pairs = pairwise(chain(s, [None]))
output = []
for l in pairs:
if l[1] and l[1] in "+-":
# number is followed by a "+" or "-" --> join together
output.append("".join(l))
elif l[0] not in "+-":
# number is not followed by +/-, append the number
output.append(l[0])
return output
# checking your examples:
strings = [';1', '2+3', '32', '12-', '2+;']
[split(s) for s in strings]
# [[';', '1'], ['2+', '3'], ['3', '2'], ['1', '2-'], ['2+', ';']]
# bonus: everything in one line because why not
[[("".join(l) if l[1] and l[1] in "+-" else l[0]) for l in pairwise(chain(s, [None])) if l[0] not in "+-"] for s in strings]
# [[';', '1'], ['2+', '3'], ['3', '2'], ['1', '2-'], ['2+', ';']]