user1743173
user1743173

Reputation:

Splitting 2 possibly negative numbers that are hyphenated

I have a Python string:

"integer-integer"

which I am trying to turn into the list

[integer,integer]

where an integer can be positive or negative and is matched by -?[0-9]+

I suspect the re.split() module is the tool for the job, however I've tried and have been unable to figure out a solution.

Here are 4 examples of input => output:

Upvotes: 4

Views: 574

Answers (1)

falsetru
falsetru

Reputation: 369324

Using positive lookbehind assertion:

>>> import re
>>> def f(s):
...     return list(map(int, re.split(r'(?<=\d)-', s)))
...
...
>>> f("0-23")
[0, 23]
>>> f("3--7")
[3, -7]
>>> f("-3-7")
[-3, 7]
>>> f("-3--7")
[-3, -7]

The pattern will match - only if it is preceded by digit (\d).

You can omit list(..) if you use Python 2.x.

Upvotes: 6

Related Questions