1

Why is it that when I run the following in the python interpreter

re.findall(r'^-?[0-9]+$', "[50, 4]")

I get [] as the result? If I'm not mistaken this should return [50, 4].

1
  • What about this ast.literal_eval("[50, 4]") ? Commented Apr 4, 2015 at 5:14

1 Answer 1

2

You are using ^...$. They mean the beginning and the ending of the string. So, you are actually trying to find out if the entire string (from the starting till the ending) is full of numbers. Just drop them and you will get what you wanted

>>> re.findall(r'-?[0-9]+', "[50, 4, -123]")
['50', '4', '-123']

If you want to convert all of them to actual numbers, then apply int function with a list comprehension, like this

>>> [int(num) for num in re.findall(r'-?[0-9]+', "[50, 4, -123]")]
[50, 4, -123]
Sign up to request clarification or add additional context in comments.

1 Comment

thefourtheye hit the nail on the head. That's why I'm using regular expressions over literaleval.

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.