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 Regular Expressions in Python Introduction to Regular Expressions Negated Numbers

Richard Lu
Richard Lu
20,185 Points

Negating numbers that are spread out

Hi, I am having trouble finding out how to find numbers that are spread out. An example would be trying to find the numbers 1, 5, 7, 9. The code below finds all the numbers from 5-7, but what If i don't want 6? How would I go about it?

negate.py
import re

string = '1234567890'

good_numbers = re.findall(r'[5-7]', string, re.X)

1 Answer

Dan Johnson
Dan Johnson
40,532 Points

If you're looking to grab the numbers individually you could do something like this:

re.findall(r"1|5|7|9", string)

Or

re.findall(r"[1579]", string)

This will match those digits and prevent grouping them if they're adjacent, e.g. "150" will map to '1' and '5' instead of "15".

Richard Lu
Richard Lu
20,185 Points

Hi Dan,

Thanks for the fast response! The problem I am getting is if I were to do:

string = "1234567890"
re.findall("[^1579]", string)

I'd get back: ['0', '234', '6', '8']

I'd like it to come back as 1 entire string. How do I accomplish this?

Dan Johnson
Dan Johnson
40,532 Points

Since you'll be dealing with separated groups of numbers I'm thinking something like this would be the easiest solution:

"".join(re.findall("[^1579]", string))

This will capture all the matches as before but concatenate them into one string again.

Richard Lu
Richard Lu
20,185 Points

Thanks Dan! I figured that was the easiest way to do it. If only it came back all at once... haha