0

Given string "5mins", I want to separate them something like [5, 'mins']. I have tried doing:

>>> re.findall(r"\d+|\D+", '5mins')
['5', 'mins']

which seems to do good but:

>>> def separate(string):
...    return re.findall(r"\d+|\D+", string)
...
>>> print(separate('3hours'))
['3', 'hours']
>>> print(separate('7secs'))
['7', 'secs']
>>> print(separate('now'))
['now']

The problem with this method is I get ValueError if I have done assignment:

>>> number, unit = separate('now')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

The all I here want is to get a list of number and unit. If there is no number then I should get an empty string, so that I can process the time further.

Additionally it's good if number is not a string, like above separate() function returns.

1
  • No, it's still a string, even if it contains a number. Commented Jul 25, 2013 at 5:58

1 Answer 1

7
>>> re.match(r"(\d+)?(\D+)?$", '5mins').groups()
('5', 'mins')
>>> re.match(r"(\d+)?(\D+)?$", 'now').groups()
(None, 'now')
Sign up to request clarification or add additional context in comments.

2 Comments

Dealing with regex has always been difficult to me. I usually run away form regex. Where did you learnt it? :)
The hard way. Practice, practice, practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.