Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Separate number from arbitrary position in string

I wouldn't usually ask something like this, but finding decent information seems to be slow going. I'm curious what the best approach to separating numerical values from a string would be. It shouldn't matter where in the string the numbers are found, or whether they are int or float values. The string will have unknown amounts of spaces, but the numbers will always follow a space. There could be more than one set of numbers contained within the string. I want to keep the text and the numbers as separate items in a list.

I'm hoping for a way to avoid regex as much as possible, though, I'm not sure if there is even another alternative. I would prefer to figure it out on my own with a little direction or advice but, if it's regex, I might need it to be a bit more specific, as my understanding is rudimentary at best.

1 Answer

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

Unless someone else has written this function in the Python library, which to my knowledge there's none, the regular expression is the only answer to this kind of problem.

You may use the re.findall function to do that. Here's a short example.

s = "today's temp is 32C, the current time is 15:22."

s is example string. And to filter out all the integer from it, you can do the following

import re
re.findall("\d+", s)    # => ['32', '15', '22']

Now, it's pretty simple to just filter out all the integer, but you want it to work with both int & float, then you have to figure out how to expand the regex to include matching of the floating point number; additionally, you also need to consider the +/- sign that might come before the number.

William Li - I appreciate the response, and I sort of expected it to be an answer along those lines. Thanks for giving a bit of direction.